线程的五大状态

目录

线程五大状态

线程使用的方法

一、线程停止

二、线程休眠

三、线程礼让

四、线程强制执行


线程五大状态

5个状态:创建、就绪、阻塞、运行、死亡

线程使用的方法

一、线程停止

注:一般不推荐用stop或者destroy强制停止,推荐运用标志位进行判断,让线程自己停下来

//线程停止
    //一般不推荐用stop或者destroy强制停止,推荐运用标志位进行判断,让线程自己停下来
public class ThreadDemo07 implements Runnable {
private boolean flag=true;
    @Override
    public void run() {
        while (flag) {
            System.out.println("线程进行中" );
        }

    }

    public static void main(String[] args)  {

        ThreadDemo07 td=new ThreadDemo07();
new Thread(td).start();
//for循环也算是一个线程
        for (int i = 0; i < 100; i++) {
            System.out.println("main"+i);
            if(i==50){
                //调用stop方法,改变标志位,让线程停止
td.stop();

                System.out.println("线程停止了");

            }
        }


    }
    //设置一个公开的标志位,让线程停止
    public void stop() {
        this.flag=false;

    }

}

二、线程休眠

1.sleep(时间)指定当前线程阻塞的毫秒数;

2.sleep存在异常InterruptedException;

3.sleep时间达到后线程进入就绪状态;

4.sleep可以模拟网络延时,倒计时等;

5.每一个对象都有一个锁,sleep不会释放锁;

用处:放大问题的发生性,CPU处理太快会导致其他线程无法进行调度

//线程倒计时
public class ThreadDemo08_ThreadSleep {
    public static void main(String[] args) throws InterruptedException {
        //时间倒计时
        //不加睡眠,while语句会不断循环打印当前时间,打印速度很快
        Date nowTime = new Date(System.currentTimeMillis());//获取系统当前时间
        System.out.println("第一次获取时间为"+new SimpleDateFormat("HH:mm:ss").format(nowTime));
        while (true) {
            try {
                Thread.sleep(1000);
                //规定时间格式
                String formatNowTime = new SimpleDateFormat("HH:mm:ss").format(nowTime);
                System.out.println("时间倒计时:"+formatNowTime);//打印出睡眠后的时间
                //再次获取系统当前时间
                nowTime = new Date(System.currentTimeMillis());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        
//  tenDown();
    }

    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        Integer num = 10;
        while (true) {
            Thread.sleep(1000);
            System.out.println("时间倒数:" + num--);
            if (num <= 0) {
                break;
            }
        }
    }
}

三、线程礼让

原理:将当前正在运行的线程暂停,但不阻塞,将线程运行状态改为就绪状态。

注:礼让不一定成功,主要还是的看CPU对线程如何进行调度

//线程礼让
    //礼让不一定成功,主要还是的看CPU对线程如何进行调度
public class ThreadDemo09_yield {
    public static void main(String[] args) {
       MyYield my=new MyYield();
       new Thread(my,"a").start();
 new Thread(my,"b").start();
    }

}
//单独写一个线程
class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程执行");
        //线程礼让语句
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程执行");
    }
}

四、线程强制执行


    原理:执行join方法后,其他线程会被阻塞,等“大哥“线程执行完后,其他线程才会进入就绪状态

//线程强制执行
    //执行join方法后,其他线程会被阻塞,等“大哥“线程执行完后,其他线程才会进入就绪状态
public class ThreadDemo10_join implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println("我是大哥,等我执行完你在执行"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //创建线程
        ThreadDemo10_join tj=new ThreadDemo10_join();
      Thread thread=new Thread(tj);//线程指定
thread.start();

        //主线程
        for (int i = 0; i < 100; i++) {
            //在10循环之前,线程和主线程也是无序调度状态
            if(i==10) {
                thread.join();//插队
            }
            System.out.println("main"+i);
        }
    }


}

五、观测线程执行状态

注:死亡之后的线程不能再启动第二次

 

//观测线程状态
public class ThreadDemo11_status {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println("sleep-------");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程执行的任务"+i);
            }

        });
        //未启动前的状态
        Thread.State state = thread.getState();
        System.out.println("启动前的状态"+state);//NEW(新生线程)
        //启动后的状态
        thread.start();
        state = thread.getState();
        System.out.println("运行中的状态"+state);//线程运行中
        while (state != Thread.State.TERMINATED) {//只要线程不终止,就一直输出状态
            Thread.sleep(999);
            state = thread.getState();//实时获取线程的状态,以便下次循环进行判断
            System.out.println(state);
        }
        //线程完成后的状态
          state=thread.getState();
        System.out.println("线程结束后的状态"+state);
    }
}

 本文章主要记录了线程的五大状态:新建、就绪、等待、运行、阻塞,以及线程礼让,线程强制执行的方法,针对不同的状态场景给出了对应的例子,有更好的建议也希望可以提出,共同进步!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值