Yvonne Chu
Yvonne Chu

Reputation: 65

How to cause InterruptedExpection when using join() for Java thread?

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

Answers (1)

Mark Peters
Mark Peters

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

Related Questions