编程知识 cdmana.com

控制线程的终止

public class Terminate implements Runnable{
    public boolean flag=true;
    public String name;

    public Terminate(String name) {
        this.name = name;
    }
    int i=0;
    @Override
    public void run() {
        while(flag){
            System.out.println(name+"-->"+i++);
        }

    }
//对外提供方法改变标识
    void terminate(){
       this.flag=false;


    }

    public static void main(String[] args) {
        Terminate t=new Terminate("c");
        new Thread(t).start();


        for (int i = 0; i < 100; i++) {
            if(i==80){
                t.terminate();//控制线程的终止//关键的一步骤
                System.out.println("cgama over");

            }
            System.out.println("main-->"+i);

        }
    }
}

版权声明
本文为[8Years]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4583813/blog/4713120

Scroll to Top