Java多线程(二):线程的六种状态

线程的六种状态

线程一共有六种状态,分为 new、runnable、blocked、waiting、Timed waiting、terminated。
rWB2Ke.png

new状态
Thread thread = new Thread(new SleepInterrupted());

当前就处在new状态

Runnable状态
thread.start();

这时进入Runnable状态(Runnable状态既有等待执行的时候也有正在执行的时候)

Blocked、Waiting、Timed_Waiting状态
public class BLockedWaitingTimedWating implements Runnable{

    public static void main(String[] args) {
        BLockedWaitingTimedWating runnable = new BLockedWaitingTimedWating();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
        System.out.println(thread2 .getState());

        try {
            Thread.sleep(1300);
        } catch (InterruptedException  e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
    }

    @Override
    public void run() {
        syn();
    }

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

}

运行结果

TIMED_WAITING
BLOCKED
WAITING

当两个线程竞争同一把锁,一个线程需要等待另一个线程释放锁时,此时这个线程的状态是blocked状态。当线程调用了类似wait()方法时,此时线程状态是waiting状态。当线程调用了类似Thread.sleep(2000)这样的方法时,此时线程的状态是Timed waiting状态。

Terminated状态

当线程运行结束或者意外终止,此时线程进入terminated状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值