Java多线程多线程的状态

参考官网文档:

获取状态的办法:

Thread.getState()

枚举解释:

NEW:

创立线程未启动start办法;

Thread thread = new Thread();

RUNNABLE:

执行了该线程的start办法,在Java虚拟机中执行,但有可能在期待操作系统的其它资源,比方CPU;

thread.start();

BLOCKED:

当一个线程期待一个monitor锁的时候,状态为BLOCKED,比方被synchronized关键字润饰的办法或代码块,如下示例:


public class ThreadStateBlockTest implements Runnable {
    public static void main(String[] args) {
        ThreadStateBlockTest threadStateBlockTest = new ThreadStateBlockTest();
        Thread thread1 = new Thread(threadStateBlockTest);
        thread1.start();
        Thread thread2 = new Thread(threadStateBlockTest);
        thread2.start();
        System.out.println("thread1 state: " + thread1.getState());
        System.out.println("thread2 state: " + thread2.getState());
    }
​
    @Override
    public void run() {
        blockMethod();
    }
​
    /**
     * 阻塞的办法
     */
    private synchronized void blockMethod() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

执行后果:

thread1 state: TIMED_WAITING
thread2 state: BLOCKED

线程1,2同时执行1先拿到了monitor锁进入synchronize润饰的办法,此时sleep不能立刻执行实现,线程2再进入就是期待获取monitor锁,状态为BLOCKED

WAITING:

TIMED_WAITING:

调用了Object.wait()办法后,以后线程会进入WAITING状态;

调用了Object.wait(time)或Thread.sleep(time)则线程会进入TIMED_WAITING;

TERMINATED:

Thread state for a terminated thread. The thread has completed execution.

线程的run办法执行完结;

线程的生命周期

如图:

新建线程后进入NEW状态,NEW只能进入RUNNABLE,RUNNABLE执行run办法完结进入TERMINATED,3个状态不可逆;

右侧为3个阻塞状态:

如果run办法遇到synchronize润饰的代码块或办法却没有取到monitor锁就进入BLOCKED状态;

BLOCKED取到monitor能够再次进入RUNNABLE状态;

RUNNABLE状态执行了obj的wait()或Thread.join()办法进入WAITING状态;

如果有其它线程唤醒调用了notify()或notifyAll()办法则再次进入RUNNABLE状态;

TIMED_WAITING同WAITING,是带time入参的的办法:sleep(time), wait(time),join(time);

wait()、notify()、notifyAll()

wait()办法做了什么?

获取到monitor锁的线程,执行了wait办法后会放弃锁,进入期待状态;

notify()和notifyAll()?

前者唤醒一个期待的线程(无奈指定,线程调度器自调度),后者唤醒所有期待的线程,而后再抢锁;

sleep(time)并不会开释锁,time超时后会继续执行;

须要阐明的一点是WAITING状态可能变为BLOCKED状态,场景如官网文档里对BLOCKED状态的解释

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

前半句了解就是进入synchronized代码库前期待monitor锁时为BLOCKED状态,后半句不太好了解,具体了解如下:

  1. 以后线程取到了锁进入了同步代码块RUNNABLE状态
  2. 调用了wait办法开释了锁,进入期待WAITING状态
  3. 收到其它线程的唤醒告诉(notiify)
  4. 须要从新获取锁进入代码块儿在之前wait的中央继续执行,但不能立即获取锁,即进入BLOCKED状态;

参考官网文档:

https://docs.oracle.com/en/ja…

— END —

马上关注    /    码上杂谈

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理