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();
}
}