/**
* Created by JuTao on 2017/2/4.
* 如何中止一個線程
*/
public class ThreadDone {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable=new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread.sleep(1000);
//僅僅利用flag並不能使線程立刻中止,當run方法中有耗時操作時會等待執行完成才結束
myRunnable.flag=false;
thread.interrupt();
}
private static class MyRunnable implements Runnable {
//立刻同步到子線程中
private volatile boolean flag = true;
@Override public void run() {
while (flag&&!Thread.interrupted()) {
System.out.println("running");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
//e.printStackTrace();
//thread.interrupt()執行后會立刻進入catch
return;
}
}
}
}
}