线程停止的方法

使用一个标志位进行终止,当flag=false时,终止线程运行

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

    }

具体方法如下:

package com.demo01;

//测试stop
//建议线程正常停止,利用次数,不建议死循环
//建议使用标志位,设置一个标志位
//不要使用stop或destory等过时方法或jdk不建议使用的方法
public class ThreadStop implements Runnable{
//    1.设置一个标识位
    private boolean flag=true;
    @Override
    public void run() {
        int i=0;
        while(flag){
            System.out.println("thread"+i++);
        }

    }

//2.设置一个公开的方法停止线程,转换标识位
    public void stop(){
        this.flag=false;
    }
    public static void main(String[] args) {
        ThreadStop teststop=new ThreadStop();
        new Thread(teststop).start();
        for(int i=0;i<1000;i++){
            System.out.println("main"+i);
            if(i==900){
//                调用stop方法,切换标识位,让线程停止
                teststop.stop();
                System.out.println("线程停止");

            }
        }

    }
}

 

posted on 2023-03-02 20:39  啥123  阅读(11)  评论(0编辑  收藏  举报