我有这段代码:
public class ThreadInteraction {
public static void main(String[] argv) {
System.out.println("Create and start a thread t1, then going to sleep...");
Thread1 t1 = new Thread1();
t1.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e.toString());
}
//let's interrupt t1
System.out.println("----------- Interrupt t1");
t1.interrupt();
for(int i =0; i<100; i++)
System.out.println("Main is back");
}
}
class Thread1 extends Thread {
public void run() {
for(int i =0; i<10000; i++)
System.out.println(i + "thread1");
}
}
似乎 t1.interrupt()
不起作用,因为在我的输出中出现了所有 10000 t1 打印。我做错了什么吗?
最佳答案
Thread.interrupt()
实际上并没有停止任何东西。此方法旨在仅设置线程的中断状态,但您必须检查它。这是您应该如何组织代码以使其工作:
public void run() {
for (int i = 0; i < 10000; i++) {
if (interrupted()) break;
System.out.println(i + "thread1");
}
}
Thread.interrupted()
在这里清除了中断状态,这是可以的,因为我们直接控制线程。如果您尝试检测中断,例如,在 java.util.concurrent 中。 Callable
运行在线程池的一个线程上,那么最好使用 Thread.currentThread().isInterrupted();
因为你不知道线程中断策略.
关于java 6线程中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10266834/