Let's say I have classes like those: Foo.java:
public class Foo implements Runnable{
public void run(){
try{
sleep(3000);
System.out.println("Slept for 3s");
}catch(InterruptedException e){
Thread.currentThread().interrupt();
System.out.println("Exception handled from Foo");
}
}
public void terminate(){
Thread.currentThread().interrupt();
}
}
Bar.java:
public class Bar implements Runnable{
private Foo f;
public Bar(Foo f){
this.f = f;
}
public void run(){
System.out.println("Interrupting Foo");
f.terminate();
System.out.println("Interrupted Foo");
try{
sleep(4000);
System.out.println("Slept for 4s");
}catch(InterruptedException e){
Thread.currentThread().interrupt();
System.out.println("Exception handled from Bar");
}
}
}
Test.java:
public class Test{
public static void main(String[] args){
Foo f = new Foo();
Bar b = new Bar(f);
new Thread(f).start();
new Thread(b).start();
System.out.println("Test end");
}
}
When I wrote this code I expected the output to be like:
Test end
Interrupting Foo
Exception from Foo handled
Interrupted
Slept for 4s
But instead of above I got:
Test end
Interrupting Foo
Interrupted
Exception from Bar handled
Slept for 3s
Story behind this code is that in my application I need one Thread/Runnable to interrupt another anonymous Thread running another Runnable instance to which I have access. Knowing that I could interrupt a Thread from inside Runnable with Thread.currentThread.interrupt() (learned from the Internet) I thought that calling this in a method of the Runnable I want to stop and then calling this method on its instance in another Thread would interrupt it. But as shows the example above it is interrupting the Thread which called the method instead of Thread that runs the Runnable in which this method is defined. Knowing that I know nothing about how Thread.currentThread.interrupt() is working and that it's not working as I expected I have a few questions:
1. From how this example works I assume that Thread.currentThread.interrupt() interrupts the Thread that is executing the function in which it is called and not the one that is running the instance on which the function was called. Is that right? If not how does it work?
2. (most important) Is there a way to interrupt a Thread by calling a method of its Runnable from another Thread? If yes - how is it done? If not - do I have to have access to Thread instance to interrupt it or would it be better if Foo just extended Thread instead of implementing Runnable?
3. Why is exception from Bar catched if the interrupt is called before sleep?