Intrrupte只是设置了一下线程的中断状态,并不是实际的停止线程。具体见下面的例子:
public class InterruptedTest {
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
if (Thread.currentThread().isInterrupted()) {
System.out.println("aa");
break; //退出循环
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
//sleep方法抛出这个异常之后会清除中断状态,所以需要重新设置中断状态
Thread.currentThread().interrupt();
}
}
}
};
final Thread t1 = new Thread(runnable1);
Runnable runnable2 = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
t1.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread(runnable2);
t1.start();
t2.start();
}
}