Reputation: 65
I am writing a test case and need InterruptedExpection to be thrown in the try-catch block of calling join()
. Any example?
Upvotes: 2
Views: 56
Reputation: 81114
Sure. Just call theThreadThatJoined.interrupt()
from a different thread.
public class JoinInterruptedExceptionExample {
public static void main(String[] args) {
final Thread workerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
workerThread.start();
final Thread waitingThread = new Thread(new Runnable() {
@Override
public void run() {
try {
workerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
waitingThread.start();
waitingThread.interrupt();
}
}
Upvotes: 3