【发布时间】:2019-09-25 18:47:10
【问题描述】:
假设我有这样的课程: 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");
}
}
当我编写这段代码时,我希望输出如下:
Test end
Interrupting Foo
Exception from Foo handled
Interrupted
Slept for 4s
但我得到的不是上面的:
Test end
Interrupting Foo
Interrupted
Exception from Bar handled
Slept for 3s
这段代码背后的故事是,在我的应用程序中,我需要一个 Thread/Runnable 来中断另一个运行我有权访问的另一个 Runnable 实例的匿名线程。知道我可以使用 Thread.currentThread.interrupt() 从 Runnable 内部中断一个线程(从 Internet 学习)我认为在 Runnable 的方法中调用这个我想停止,然后在另一个线程的实例上调用这个方法会打断它。但是如上面的示例所示,它正在中断调用该方法的线程,而不是运行定义该方法的 Runnable 的线程。知道我对 Thread.currentThread.interrupt() 的工作原理一无所知,而且它没有按我预期的那样工作,我有几个问题:
1. 从这个例子的工作原理来看,我假设 Thread.currentThread.interrupt() 会中断正在执行调用它的函数的线程,而不是正在运行调用函数的实例的线程。那正确吗?如果不是,它是如何工作的?
2.(最重要的)有没有办法通过从另一个线程调用它的Runnable的方法来中断一个线程?如果是 - 它是如何完成的?如果没有 - 我是否必须有权访问 Thread 实例才能中断它,或者如果 Foo 只是扩展 Thread 而不是实现 Runnable 会更好吗?
3. 为什么在睡眠前调用中断会捕获Bar的异常?
【问题讨论】:
标签: java multithreading interrupt runnable