我得到了这段代码:
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");
}
}在我的输出中,似乎所有的10000 t1 print都显示为t1.interrupt()不起作用。我做错了什么吗?
发布于 2012-04-22 17:42:42
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();,因为您不知道线程中断策略。
发布于 2012-04-22 17:42:17
仅当目标线程处于非常特定的状态时,Thread.interrupt才会导致其停止:
首先调用此线程的checkAccess方法,这可能导致抛出SecurityException。
如果此线程在调用Object类的wait()、wait(long)或wait(long,int)方法,或调用此类的join()、join(long)、join(long,int)、sleep(long)或sleep(long,int)方法时被阻塞,则其中断状态将被清除,并将收到InterruptedException。
如果该线程在可中断通道上的I/O操作中被阻塞,则该通道将被关闭,该线程的中断状态将被设置,并且该线程将接收ClosedByInterruptException。
如果这个线程在Selector中被阻塞,那么线程的中断状态将被设置,并且它将立即从选择操作返回,可能返回一个非零值,就像调用选择器的唤醒方法一样。
如果前面的条件都不成立,则将设置此线程的中断状态。
如果您希望线程提前退出该循环,则需要检查线程中的isInterrupted。
for(int i =0; i<10000 && !isInterrupted(); i++)https://stackoverflow.com/questions/10266834
复制相似问题