App下載

分享Java線程狀態(tài)中一些容易混淆,產(chǎn)生誤解的內(nèi)容

猿友 2021-08-04 14:33:03 瀏覽數(shù) (1950)
反饋

本篇文章主要分享了關(guān)于在 Java 線程狀態(tài)下,一些容易混淆,容易踩到的坑,例如 BLOCKED 和 WAITING 之間的區(qū)別。下面,將會(huì)通過(guò)詳細(xì)的實(shí)例代碼為大家講解這些 Java 線程狀態(tài)容易誤解的問(wèn)題。

BLOCKED 和 WAITING 的區(qū)別

BLOCKED 和 WAITING 兩種狀態(tài)從結(jié)果上來(lái)看,都是線程暫停,不會(huì)占用 CPU 資源,不過(guò)還是有一些區(qū)別的

BLOCKED

等待 Monitor 鎖的阻塞線程的線程狀態(tài),處于阻塞狀態(tài)的線程正在等待 Monitor 鎖進(jìn)入 synchronized   Block 或者 Method ,或者在調(diào)用 Object.wait 后重新進(jìn)入同步塊/方法。簡(jiǎn)單的說(shuō),就是線程等待 synchronized 形式的鎖時(shí)的狀態(tài)

下面這段代碼中, t1 在等待 t0 的鎖釋放(synchronized代碼塊執(zhí)行完成),那么此時(shí) t1 的狀態(tài)就是 BLOCKED

Object lock = new Object();
Thread t0 = new Thread(new Runnable() {
    @Override
    public void run() {
        synchronized (lock){
            System.out.println("t0 acquire lock success");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
t0.start();
Thread.sleep(100);
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        synchronized (lock){
            System.out.println("t1 acquire lock success");
        }
    }
});
t1.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("t1 state: "+t1.getState());
System.out.println("done.");

//output
t0 acquire lock success
t0 state: TIMED_WAITING
t1 state: BLOCKED
done.
t1 acquire lock success

WAITING

等待中的線程狀態(tài),下面幾個(gè)方法的調(diào)用會(huì)導(dǎo)致線程進(jìn)入 WAITING 狀態(tài):

  • Object.wait()
  • Thread.join()
  • LockSupport.park()

WAITING 狀態(tài)中的線程在等待其他線程執(zhí)行某些操作,比如在某個(gè)對(duì)象上調(diào)用 Object.wait() 的線程正在等待另一個(gè)線程在該對(duì)象上調(diào)用 Object.notify() 或 Object.notifyAll()。為 Thread.join() 的線程正在等待指定的線程停止。
下面這段代碼中,t0 在通過(guò) synchronized 獲取了 lock 對(duì)象的鎖之后,進(jìn)行了 wait 操作,導(dǎo)致 t0 進(jìn)入 WAITING 狀態(tài):

Object lock = new Object();
Thread t0 = new Thread(new Runnable() {
    @Override
    public void run() {
        synchronized (lock){
            System.out.println("t0 acquire lock success");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
t0.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("done.");

//output
t0 acquire lock success
t0 state: WAITING
done.

區(qū)別

JAVA 中除了 synchronized Block/Method 的鎖,還提供了 JUC 下的鎖實(shí)現(xiàn), juc.lock 下的鎖功能更強(qiáng)大。比如支持中斷,支持重入/非重入,公平/非公平等;但是 juc 下的鎖和 synchronized 的實(shí)現(xiàn)可是不太一樣的
比如下面這段代碼,同樣是等待鎖,可是和synchronized等待鎖的狀態(tài)還不一樣:

ReentrantLock reentrantLock = new ReentrantLock();
Thread t0 = new Thread(new Runnable() {
    @Override
    public void run() {
        reentrantLock.lock();

        System.out.println("t0 acquire lock success");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
});
t0.start();
Thread.sleep(100);
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        reentrantLock.lock();
        System.out.println("t1 acquire lock success");
    }
});
t1.start();
Thread.sleep(100);
System.out.println("t0 state: "+t0.getState());
System.out.println("t1 state: "+t1.getState());
System.out.println("done.");

//output
t0 acquire lock success
t0 state: TIMED_WAITING
t1 state: WAITING
done.

同樣是加鎖,在 JUC 的鎖實(shí)現(xiàn)下線程狀態(tài)不太一樣,所以在觀察線程狀態(tài)時(shí),不止是 BLOCKED 的狀態(tài)才是等待鎖, WAITING/TIMEWAITING 的狀態(tài)仍然可能是等待鎖的狀態(tài)
不過(guò) JUC 下的鎖實(shí)現(xiàn),讓線程暫停/等待的核心方法還是 LockSupport.park , jstack 對(duì)于 PARKING 形式的 WAITING 會(huì)有標(biāo)注,所以在線程 stack 時(shí)還是能一眼看出來(lái)的:

//這里顯示了等待類型
"Thread-0" #11 prio=5 os_prio=31 tid=0x00007f9308110000 nid=0x5c03 waiting on condition [0x0000700007fc3000]
   java.lang.Thread.State: WAITING (parking)//這里雖然是WAITING,但還是標(biāo)注了是parking類型的
        at sun.misc.Unsafe.park(Native Method)

而 synchronized 形式的鎖在 jstack 下的輸出會(huì)有所區(qū)別:

//這里顯示了等待類型為monitor
"Thread-1" #12 prio=5 os_prio=31 tid=0x00007f833d919800 nid=0x5a03 waiting for monitor entry [0x00007000035af000]
   java.lang.Thread.State: BLOCKED (on object monitor)//這里是BLOCKED狀態(tài),同時(shí)顯示了monitor的歸屬

所以在觀察線程狀態(tài)時(shí),需要注意Object.wait()這種WAITING和juc下鎖導(dǎo)致的WAITING的區(qū)別

RUNNABLE 真的是 RUNNABLE 嗎?

下面是一段 jstack 輸出的例子,該線程現(xiàn)在正在執(zhí)行 socketRead0 方法(Native),并且是 RUNNABLE 狀態(tài)

"RMI TCP Connection(2)-192.xxx.xx.xx" daemon prio=6 tid=0x000000000a3e8800 nid=0x158e50 runnable [0x000000000adbe000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
- locked (0x00000007ad784010) (a java.io.BufferedInputStream)
at java.io.FilterInputStream.read(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

但其實(shí)這里的 RUNNABLE 只是 JAVA 層面的線程狀態(tài),在操作系統(tǒng)或進(jìn)程角度來(lái)看,該線程還是 WAITING 的狀態(tài); SocketInputStream 是一個(gè) BIO 的實(shí)現(xiàn),當(dāng)沒(méi)有收到數(shù)據(jù)(或者說(shuō)沒(méi)有準(zhǔn)備好可讀的數(shù)據(jù))時(shí)會(huì)發(fā)生阻塞,可這個(gè)阻塞在JAVA線程狀態(tài)里是 RUNNABLE 的狀態(tài),不過(guò)他并不會(huì)占用用戶態(tài)的 CPU 時(shí)間片,內(nèi)核在接受到數(shù)據(jù)后會(huì)結(jié)束這個(gè)阻塞


到此這篇關(guān)于Java線程狀態(tài)一些容易混淆,誤解的問(wèn)題內(nèi)容的文章就介紹到這了,想要了解更多相關(guān) Java 線程的內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持!


0 人點(diǎn)贊