为什么我的thread终止( thread.interrupt();)无效, 还是一直输出
public class App
{
public static void main( String[] args ) throws InterruptedException {
Thread thread = new Thread(new A());
thread.start();
System.out.println(" start===========");
Thread.sleep(3000);
System.out.println(" sleep===========");
thread.interrupt();
System.out.println(" interrupt===========");
Thread.sleep(3000);
System.out.println(" stop===========");
}
}
class A extends Thread {
@Override
public void run() {
boolean result = false;
while (!result) {
System.out.println("=====thread run");
long time = System.currentTimeMillis();
if (System.currentTimeMillis() - time < 1000) {
// break;
}
}
System.out.println("while end");
}
}
很多初学者都会误认为,线程调用了thread.interrupt()之后就立马停止当前行为,不再往下执行。其实不然,interrupt 只是将当前线程设置为中断线程,在多线程环境下用于互相调度协作,一般与thread.isInterrupted()来使用。 比如:if(thread.isInterrupted()){ /线程被标记中断了,干一些你需要干的业务/ }。需要注意的是:当前程出于阻塞状态的时候,调用interrupt方法回抛interruptException异常。