前言
今天看源碼的時候遇到這樣一個場景,某線程里面的邏輯需要等待異步處理結(jié)果返回后才能繼續(xù)執(zhí)行。或者說想要把一個異步的操作封裝成一個同步的過程。這里就用到了線程等待喚醒機制,下面具體看一下。
等待喚醒機制示例
下面代碼是一個簡單的線程喚醒機制示例,主要就是在Activity啟動的時候初始化并start線程,線程start后會進入等待狀態(tài),在onResume方法中執(zhí)行notify方法喚醒線程。通過這樣的方式模擬異步喚醒線程——線程等待喚醒機制。
public class ThreadDemo extends AppCompatActivity {
private final static String TAG = ThreadDemo.class.getSimpleName();
private Object mLock = new Object();
private Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (mLock) {
Log.i(TAG,"state 1 = " + mThread.getState());
try {
mLock.wait(10 * 1000);
Log.i(TAG,"state 2 = " + mThread.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"state 3 = " + mThread.getState());
mThread.start();
Log.i(TAG,"state = 4 " + mThread.getState());
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
synchronized(mLock) {
Log.i(TAG,"state = 5 " + mThread.getState());
mLock.notify();
Log.i(TAG,"state = 6 " + mThread.getState());
}
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG,"state = 7 " + mThread.getState());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
Log如下:
09-11 17:31:29.577 32658-32658/com.android.peter.threaddemo I/ThreadDemo: state 3 = NEW
09-11 17:31:29.578 32658-32658/com.android.peter.threaddemo I/ThreadDemo: state = 4 RUNNABLE
09-11 17:31:29.578 32658-32695/com.android.peter.threaddemo I/ThreadDemo: state 1 = RUNNABLE
09-11 17:31:29.588 32658-32658/com.android.peter.threaddemo I/ThreadDemo: state = 5 TIMED_WAITING
09-11 17:31:29.588 32658-32658/com.android.peter.threaddemo I/ThreadDemo: state = 6 BLOCKED
09-11 17:31:29.588 32658-32695/com.android.peter.threaddemo I/ThreadDemo: state 2 = RUNNABLE
09-11 17:31:40.276 32658-32658/com.android.peter.threaddemo I/ThreadDemo: state = 7 TERMINATED
為什么可以這么用
我當(dāng)時看完后產(chǎn)生一個疑問,就是run方法的synchronized代碼塊不是被鎖住了處于TIMED_WAITING狀態(tài)了么,按理說同步鎖應(yīng)該沒有被釋放啊,為什么onResume中的synchronized代碼塊可以被執(zhí)行從而喚醒線程。
這是因為wait是Object類的方法,當(dāng)被調(diào)用時即釋放資源也釋放鎖;而sleep是Thread類的方法,當(dāng)被調(diào)用時只釋放資源不釋放鎖。之前都是用的sleep來使線程進入TIMED_WAITING狀態(tài)的,所以一直的認(rèn)知是synchronized代碼段執(zhí)行完畢才會釋放鎖,然后再執(zhí)行下一個synchronized代碼段。經(jīng)過本次學(xué)習(xí)對synchronized同步機制有了新的更深刻的認(rèn)識。
java線程的狀態(tài)
下面是Thread類中枚舉的六種線程狀態(tài),借此機會順便學(xué)習(xí)一下。
libcore/ojluni/src/main/java/java/lang/Thread.java
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;
}
結(jié)合上面代碼運行的log來理解一下線程的各個狀態(tài)。
NEW(初始化狀態(tài))
線程通過new初始化完成到調(diào)用start方法前都處于等待狀態(tài)。RUNNABLE(可執(zhí)行狀態(tài))
線程執(zhí)行start方法后就處于可以行狀態(tài)。BLOCKED(阻塞狀態(tài))
notify方法被調(diào)用后線程被喚醒,但是這時notify的synchronized代碼段并沒有執(zhí)行完,同步鎖沒有被釋放,所以線程處于BLOCKED狀態(tài)。直到notify的synchronized代碼段執(zhí)行完畢鎖被釋放,線程才回到wait所在的synchronized代碼段繼續(xù)執(zhí)行。WAITING(等待狀態(tài))
調(diào)用sleep或是wait方法后線程處于WAITING狀態(tài),等待被喚醒。TIMED_WAITING(等待超時狀態(tài))
調(diào)用sleep或是wait方法后線程處于TIMED_WAITING狀態(tài),等待被喚醒或時間超時自動喚醒。TERMINATED(終止?fàn)顟B(tài))
在run方法結(jié)束后線程處于結(jié)束狀態(tài)。