Java零基础学java之多线程--08线程停止


//测试stop
/*
* 1. 建议线程正常停止--->利用次数,不建议死循环
* 2. 建议使用flag标志位
* 3. 不要使用stop和destroy等过时或者JDK不建议使用的方法
*/
//用flag标志位停止线程
public class TestThreadStop implements Runnable{
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("子线程。。。。。" + i++);
        }
    }
//创建一个公开的方法停止线程,转换标志位
    public void stop() {
          this.flag = false;
    }

    public static void main(String[] args) {
        TestThreadStop testThreadStop = new TestThreadStop();
        new Thread(testThreadStop).start();
        //main主线程跑1000,子线程在主线程900标志位时停止
        for (int i = 0; i < 1000; i++) {
            System.out.println("main主线程。。。。。" + i);
            if (i==900){
                //调用stop方法切换标志位,让线程停止
                testThreadStop.stop();
                System.out.println("--------我被标志位停止了------");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/l1341886243/article/details/118345598
今日推荐