Java线程的状态

2020-01-15  本文已影响0人  ywy_袁滚滚

线程的状态

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * 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
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

状态验证

class ThreadTest {
    @Test
    fun test() {
        val thread = MyThread()
        println("thread state before start:${thread.state}")
        thread.start()
        Thread.sleep(200)   //睡200ms等待run执行完成
       println("thread state after run :${thread.state}")
    }


    class MyThread :Thread(){
        override fun run() {
            super.run()
            println("thread state on run:$state")
        }
    }
}
线程状态-NEW_RUNNABLE_TERMINATED.png
class ThreadTest {

    @Test
    fun test() {
        val lock = Object()
        val thread1 = MyThread("thread 1",lock)
        thread1.start()
        Thread.sleep(200) //等待200ms 让thread1被调度执行

        val thread2 = MyThread("thread 2",lock)
        thread2.start()
        Thread.sleep(200) //等待200ms 让thread2被调度执行 ,此时thread1已经持有锁了

        println("thread2 state :${thread2.state}")
    }


    class MyThread constructor(name: String,var lock:Object) : Thread(name) {
        override fun run() {
            super.run()
            println("$name try to hole the lock")
            synchronized(lock) {
                println("$name  hole the lock now")
                sleep(1000 * 1000)
            }
        }
    }
}
线程状态_BLOCKED.png
class ThreadTest {

    @Test
    fun test() {
        val lock = Object()
        val thread1 = MyThread("thread 1",lock)
        thread1.start()
        Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态

        println("thread1 state :${thread1.state}")
    }


    class MyThread constructor(name: String,var lock:Object) : Thread(name) {
        override fun run() {
            super.run()
            synchronized(lock){ //在调用lock之前需要使用synchronized语义绑定住被wait/notify的对象
                println("$name state:$state")
                lock.wait()
                println("$name state:$state")
            }
        }
    }
}
线程状态_WAITING.png
class ThreadTest {

    @Test
    fun test() {
        val lock = Object()
        val thread1 = MyThread("thread 1",lock)
        thread1.start()
        Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态

        println("thread1 state :${thread1.state}")

        synchronized(lock) {
            lock.notifyAll() //通知
        }

        Thread.sleep(200)
        println("thread1 state after notify:${thread1.state}")
    }


    class MyThread constructor(name: String,var lock:Object) : Thread(name) {
        override fun run() {
            super.run()
            synchronized(lock){ //在调用wait()之前需要使用synchronized语义绑定住被wait/notify的对象(获取到锁)
                println("$name state:$state")
                lock.wait()
                println("$name state:$state")
            }
        }
    }
}
线程状态_等待唤醒.png
class ThreadTest {

    @Test
    fun test() {
        val thread1 = MyThread("thread 1")
        Object().wait(1000)
        thread1.start()
        Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态
        println("thread1 state :${thread1.state}")
        Thread.sleep(1000) //等待1000ms 让线程run执行完成
        println("thread1 state :${thread1.state}")
    }


    class MyThread constructor(name: String) : Thread(name) {
        override fun run() {
            super.run()
            println("$name state:$state")
            sleep(1000)
            println("$name state:$state")
        }
    }
}
线程状态_TIMED_WAITING .png
class ThreadTest {

    @Test
    fun test() {
        val lock = Object()
        val thread1 = MyThread("thread 1",lock,false)
        thread1.start()
        Thread.sleep(200) //等待200ms 让thread1被调度执行,进入等待状态
        println("thread1 state :${thread1.state}")

        Thread.sleep(3000) //等待3000ms 让线程thread1 run能够继续执行
        thread1.condition = true //让条件满足

        Thread.sleep(2000) ///等待2000ms 确保让线程thread1 run执行
        println("thread1 state :${thread1.state}")
    }


    class MyThread constructor(name: String,var lock:Object,var condition:Boolean) : Thread(name) {

        override fun run() {
            super.run()
            synchronized(lock){
                while (!condition){
                    println("$name state:$state")
                    lock.wait(1000)
                    println("$name continue run at ${System.currentTimeMillis()}")
                }

                println("do sth when meet the conditions")
                println("$name state:$state")
            }

        }
    }
}
TIMED_WAITING.png

状态图

线程状态图.png

Object.wait、Thread.sleep、LockSupport.park、等方法的异同

在前面的状态图中列举了非常多方法,那么它们的的区别是什么呢?怎么使用它们才能保证线程的状态是符合我们的预期的(程序的功能符合预期)

关于锁的释放的补充

前面说到Object.wait是会释放锁的,那么是释放Object的锁还是释放线程持有的所有锁呢?关于Object.wait释放锁,我想你能搜到的99.9%的文章都是只说了这么一句——Object.wait是会释放锁。先来看一个例子

class ThreadTest {

    @Test
    fun test() {
        val lock = Object()
        val lock2 = Object()
        val thread = Thread1("thread 1",lock,lock2)
        thread.start()
        Thread.sleep(200)

        synchronized(lock2){  //先获取lock2看下会不会被释放
            synchronized(lock){
                lock.notifyAll()
            }
        }

        Thread.sleep(1000) //等待thread 1执行完成

        println("thread1 state :${thread.state}")
    }


    class  Thread1  constructor(name: String,var lock:Object,var lock2:Object) : Thread(name){
        override fun run() {
            super.run()
            synchronized(lock){ //持有lock2锁
                synchronized(lock2){ //持有lock2锁
                    lock.wait()

                    println("$name 被唤醒")
                }
            }

        }
    }

}

main dump信息.png thread 1 Dump信息.png
上一篇 下一篇

猜你喜欢

热点阅读