多线程-线程周期的几种状态

New 已创建但还未启动

Runnable 一旦调用start之后就是runnable(可运行) 对应了ready和running cpu在分配中也是runnable

Blocked 锁 进入synchronized修饰的代码块

Waiting

Timed Waiting

Terminated

public class NewRunnableTerminated implements Runnable{
    public static void main(String[] args) {
        Thread thread = new Thread(new NewRunnableTerminated());
        //NEW状态
        System.out.println(thread.getState());
        thread.start();
        //Runnable状态
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Runnable状态,即使是正在运行,也是Runnable状态,而不是Running
        System.out.println(thread.getState());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Terminated
        System.out.println(thread.getState());
    }

    @Override
    public void run() {
        for (int i = 0; i <10000 ; i++) {
            System.out.println(i);
        }
    }
}
public class BlockedWaitingTimedWaiting implements Runnable{
    public static void main(String[] args) throws InterruptedException {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread.sleep(10);
        Thread thread2 = new Thread(runnable);
        thread2.start();

        //Time Waiting 因为正在执行的Thread.sleep(1000)
        System.out.println("线程1的状态:"+thread1.getState());
        //Blocked 因为thread2想得到syn()的锁 却拿不到 因为线程1没有释放
        System.out.println("线程2的状态:"+thread2.getState());
        Thread.sleep(1500);
        //打印出Waiting
        System.out.println("线程1的状态:"+thread1.getState());
    }

    @Override
    public void run() {
        syn();
    }
    private synchronized void syn(){
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值