(1)中断操作是线程间的交互方式,最适合用来取消或停止任务

(2)可以用一个boolean变量来控制是否需要停止任务并终止线程。

public class 安全地终止线程 {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) throws InterruptedException {
        Runner one=new Runner();
        Thread countThread=new Thread(one,"CountThread");
        countThread.start();
        //主程序sleep1秒
        TimeUnit.SECONDS.sleep(1);
        //main线程通过中断操作使CountThread得以终止
        countThread.interrupt();//Interrupts this thread

        Runner two=new Runner();
        countThread=new Thread(two,"CountThread");
        countThread.start();
        TimeUnit.SECONDS.sleep(1);
        //通过标识位将线程终止
        two.cancel();
    }
    private static class Runner implements Runnable{
        private long i;
        private volatile boolean on=true;
        @Override
        public void run() {
            while(on&&!Thread.currentThread().isInterrupted())i++;
            System.out.println("count i="+i);
        }
        public void cancel(){
            on=false;
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

范式:

run:
while(flag&&!isInterrupted){

}
  • 1.
  • 2.
  • 3.
  • 4.

这种通过标识位或者中断操作的方式能够使线程在终止时有机会去清理资源,而不是武断地将线程停止。显得更加安全和优雅。