ab_*_*v86 2 java multithreading
我有这段代码:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
它似乎t1.interrupt()不起作用,因为在我的输出中出现所有10000 t1打印.难道我做错了什么?
Thread.interrupt()实际上不会阻止任何事情.此方法仅用于设置线程的中断状态,但您必须检查它.这是您应该如何组织代码以使其工作:
public void run() {
for (int i = 0; i < 10000; i++) {
if (interrupted()) break;
System.out.println(i + "thread1");
}
}
Run Code Online (Sandbox Code Playgroud)
Thread.interrupted()这里清除中断状态,这是好的,因为我们直接控制线程.如果您尝试检测中断,例如,在java.util.concurrent. Callable线程池的某个线程上运行中断,那么最好使用,Thread.currentThread().isInterrupted();因为您不知道线程中断策略.
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |