线程状态stop & sleep

线程停止练习代码:

package www.chen.com.state;

//测试stop
//1.建议线程正常停止,利用循环次数,不建议死循环,用循环时要加上延时,防止cpu卡死
//2.建议使用标志位,立一个flag
//3.不要使用jdk不推荐的方法,比如stop或者destroy这类过时方法
public class TestStop implements Runnable{
    //1设置一个标志位
   private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while(flag){
            System.out.println("run....Thread"+i++);
        }
    }
    //2.设置一个公开的方法停止线程
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();

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

            }
        }
    }
}

线程休眠练习代码:

package www.chen.com.state;

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟倒计时
public class TestSleep {

    public static void main(String[] args) {
        boolean flag = true;

        //打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间


            while (flag) {
                for (int i = 0; i <=10 ; i++) {
                    if (i==10){
                        flag = false;
                    }
                try {
                    Thread.sleep(1000);
                    //打印系统当前时间
                    System.out.println(new SimpleDateFormat("YYYY:HH:mm:ss").format(startTime));
                    startTime = new Date(System.currentTimeMillis());//更新当前时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    }
                }
            }
    }
    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;

        while(true){
            Thread.sleep(1000);
            System.out.println(num--);

            if (num<=0){
                break;
            }
        }
    }
}
posted @ 2021-03-14 18:02  恶的反思  阅读(118)  评论(0)    收藏  举报