javaSE之多线程之使用标志位控制线程停止

package state;

public class TestStop implements Runnable {
    
    


    //设置一个标志位
    private boolean flag = true;


    @Override
    public void run() {
    
    
        int i=0;
        while (flag){
    
    
            System.out.println("run.....Thread"+i++);
        }
    }

    //设置一个公开的方法,转换标志位
    public void stop(){
    
    
        this.flag=false;
    }


    public static void main(String[] args) {
    
    

        TestStop thread3 = new TestStop();

        new Thread(thread3).start();

        for (int i = 0; i <1000 ; i++) {
    
    
            System.out.println("main"+i);
            if (i==900){
    
    
                //调用stop方法,切换标志位
                thread3.stop();
                System.out.println("线程该停止了");
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_42794826/article/details/108957067