Reputation: 1160
Why I don't get InterruptedException
in the main
thread? Here says that it throws
InterruptedException - if any thread has interrupted the current thread. So why I don't get caught InterruptedException
when I interrupted thread in the run()
method?
public class Test
{
public static void main(String[] args)
{
try
{
Thread t1 = new Test1();
t1.start();
t1.join();
}
catch (InterruptedException e)
{
System.out.println("exception has been caught");
}
}
}
class Test1 extends Thread
{
public void run()
{
// to ensure that ```t1.join``` in the ```main``` thread executed earlier than ```Thread.currentThread().interrupt();```
for (int i = 0; i < 10_000; i++) {}
Thread.currentThread().interrupt();
}
}
Upvotes: 2
Views: 391
Reputation: 103273
Thread.currentThread().interrupt()
This is useless: You're interrupting your own thread, there is never any point in doing this. All this does is raise the interrupt flag on your own thread, meaning, the next time your thread executed any method that is declared to throw interruptedexception, it will immediately do so. Thus: pointless.
What you really wanted to do was interrupt the other thread. t1.join()
is an operation that will 'sleep' this thread until t1
finishes. This is an interruptable operation: You do that not by interrupting t1, but by interrupting your main thread.
Here is an example:
public class Test
{
public static void main(String[] args)
{
try
{
Test1 t1 = new Test1();
t1.threadToInterrupt = Thread.currentThread();
t1.start();
t1.join();
}
catch (InterruptedException e)
{
System.out.println("exception has been caught");
}
}
}
class Test1 extends Thread
{
Thread threadToInterrupt;
public void run()
{
for (int i = 0; i < 10_000; i++) {}
threadToInterrupt.interrupt();
}
}
Upvotes: 2