【狂神数Java】线程停止,线程睡眠

线程状态

5大状态

  • 创建状态 new对象
  • 就绪状态 start()后就绪,但不意味着立即执行
  • 阻塞状态 Thread.sleep(),调用sleep、wait或者同步锁定时,进入阻塞,阻塞结束后,重新就绪,等待cpu调度
  • 运行状态 cpu调度后,线程开始执行,进入运行状态
  • 死亡状态 线程结束,一旦进入死亡,就不能再启动了

线程方法

终止线程

  • 不推荐使用JDK提供的stop()、destroy()方法。
  • 推荐线程自己停止下来。
  • 建议使用一个标志位进行终止变量,如:当flag=false,则终止线程运行。如:龟兔赛跑代码

终止线程例子:

public class StopThread implements Runnable {
    public StopThread(int i) {
        this.i = i;
    }

    private int i = 1;
    private boolean flag = true;

    // 定义线程,实现runnable接口
    @Override
    public void run() {
        while (flag) {
            System.out.println(Thread.currentThread().getName());
            // 延时,看输出效果
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("持续输出" + i);
        }
    }

    // 给个外部停止的方法
    public void stop() {
        this.flag = false;
    }
    
    // main方法启动
    public static void main(String[] args) {
        StopThread stopThread1 = new StopThread(1);
        StopThread stopThread2 = new StopThread(2);
        new Thread(stopThread1, "a").start();
        new Thread(stopThread2, "b").start();
        
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopThread1.stop(); // 线程a停止,线程b继续跑
    }
}

线程休眠

  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常 InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等;
  • 每一个对象都会有一个锁,sleep不会释放锁。

模拟延时

try {     
    Thread.sleep(2000);
} catch (InterruptedException e) {
        e.printStackTrace();
}

模拟时钟

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

public class CurrentTime {
    public static void main(String[] args) {

        while (true){
            try {
                // 获取当前时间
                Date starttime = new Date(System.currentTimeMillis());
                //SimpleDateFormat 格式化当前时间
                String formattime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(starttime);
                System.out.print(formattime+"\r");
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
posted @ 2021-09-16 14:15  Jie7  阅读(82)  评论(0)    收藏  举报