Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

java - Does calling Thread.interrupt() before a Thread.join() cause the join() to throw an InterruptedException immediately?

Basically, what the question title says.

Thread t = new Thread(someRunnable);
t.start();
t.interrupt();
t.join(); //does an InterruptedException get thrown immediately here?

From my own tests, it seems to, but just wanted to be sure. I'm guessing Thread.join() checks the interrupted status of the thread before doing its "wait" routine?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does calling Thread.interrupt() before a Thread.join() cause the join() to throw an InterruptedException immediately?

No it will not throw. Only if the current thread that is calling the join() method gets interrupted will join() throw InterruptedException. t.interrupt() is interrupting the thread you just started, while t.join() will only throw InterruptedException if the thread that is doing the join-ing (maybe the main thread?) is itself interrupted.

 Thread t = new Thread(someRunnable);
 t.start();
 t.interrupt();
 t.join();  // will _not_ throw unless this thread calling join gets interrupted

Also it is important to realize that interrupting a thread does not cancel it and join() is not like a Future in that it will return the exception the thread threw.

When you interrupt a thread, any calls the thread is making to sleep(), wait(), join(), and other interruptible methods will throw InterruptedException. If those methods are not called then the thread will continue running. If a thread does throw a InterruptedException in response to being interrupted and then quits, that exception will be lost unless you you used t.setDefaultUncaughtExceptionHandler(handler).

In your case, if the thread is interrupted and finishes because it returns, then the join will finish -- it will not throw an exception. Common thread code to handle an interrupt properly is as follows:

 public void run() {
    try {
       Thread.sleep(10000);
    } catch (InterruptedException e) {
       // a good pattern is to re-interrupt the thread when you catch
       Thread.currentThread().interrupt();
       // another good pattern is to make sure that if you _are_ interrupted,
       // that you stop the thread
       return;
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...