利用标志位实现线程停止

线程停止

利用转换标志位来控制线程时可能会出现偷跑问题
具体过程:

  1. A线程进入while循环体内
  2. main线程调用stop方法切换标志位,并输出
  3. A线程执行方法体内的输出

虽然main线程已经将标志位切换,但由于A线程已经进入到while循环体内,所以while循环体内的语句会继续执行下去,直到下一次循环无法进入到方法体中。
所以会造成切换后多输出一次的现象。

public class TestStop implements Runnable{
    private boolean flag=true;//标志位
    @Override
    public void run() {
        int i=0;
        while (flag){
            System.out.println(Thread.currentThread().getName()+"-->"+i++);
        }
    }
    //设置一个公开的方法停止线程,转换标志位
    public void stop(){
        this.flag=false;
    }
    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop,"A线程").start();//开启线程

        for (int i = 0; i <= 100; i++) {
            System.out.println("main-->"+i);
            if (i==90){
                /*停止线程。(这样设置,线程可能不会立即停止,有可能会多多输出一次)
                具体:线程进入while循环体内
                main线程切换标志位,并输出
                线程执行while方法体的输出,所以会产生线程多输出一次的现象
                 */
                testStop.stop();
                System.out.println("线程已停止");
            }
        }
    }
}

原文地址:https://www.cnblogs.com/code-xu/p/14169361.html