線程的狀態(tài)
操作系統(tǒng)的進(jìn)程狀態(tài)分為: 就緒、運(yùn)行中、阻塞、終止。阻塞狀態(tài)只能先變?yōu)榫途w,再變?yōu)檫\(yùn)行中。
public enum State {
/**
* Thread state for a thread which has not yet started.
* 線程還未啟動(dòng)時(shí)的狀態(tài)。
*/
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.
* 可運(yùn)行的狀態(tài)。處于可運(yùn)行狀態(tài)的線程正在Java虛擬機(jī)中執(zhí)行,
* 但它可能正在等待來自操作系統(tǒng)的其他資源,如處理器。
*/
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}.
* 等待監(jiān)視器鎖定的被阻塞線程的線程狀態(tài)。
* 處于阻止?fàn)顟B(tài)的線程正在等待監(jiān)視器鎖進(jìn)入同步塊/方法,
* 或在調(diào)用Object.wait后重新進(jìn)入同步塊/方法。
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* 等待線程的線程狀態(tài)。由于調(diào)用以下方法之一,線程處于等待狀態(tài):
*
* <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.
* 處于等待狀態(tài)的線程正在等待另一個(gè)線程執(zhí)行特定操作。
*
* 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.
* 例如:一個(gè)線程調(diào)用了一個(gè)對(duì)象上的Object.wait()方法,是在等待另外一個(gè)線程調(diào)用該對(duì)象的Object.notify或者Object.notifyAll()方法。
* 一個(gè)線程調(diào)用了Thread.join()是在等待一個(gè)特定的線程終止。
*/
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:
* 具有指定等待時(shí)間的等待線程的線程狀態(tài)。
* 使用指定的等待時(shí)間調(diào)用以下方法會(huì)使一個(gè)線程處于TIMED_WAITING狀態(tài):
* <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.
* 線程已終止。已完成執(zhí)行。
*/
TERMINATED;
}
sleep方法
- 讓線程睡眠指定的毫秒數(shù)。
- sleep不會(huì)失去任何監(jiān)視器的所有權(quán)。
- 可以被中斷。當(dāng)被中斷并拋出異常時(shí),線程的interrupted狀態(tài)會(huì)被清除。
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
* 根據(jù)系統(tǒng)計(jì)時(shí)器和調(diào)度程序的精度和準(zhǔn)確性,使當(dāng)前執(zhí)行的線程休眠(暫時(shí)停止執(zhí)行)指定的毫秒數(shù)。
* 線程不會(huì)失去任何監(jiān)視器的所有權(quán)。
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
* 如果任何線程中斷了該線程。當(dāng)異常拋出時(shí)當(dāng)前線程的interrupted狀態(tài)也將清除。
*/
public static native void sleep(long millis) throws InterruptedException;
join方法
- b線程內(nèi)部調(diào)用a.join(),說明b要等待a線程終止后再繼續(xù)執(zhí)行。
- a線程終止后,虛擬機(jī)底層會(huì)調(diào)用a.notifyAll方法將b喚醒。
- 可以被中斷。當(dāng)被中斷并拋出異常時(shí),線程的interrupted狀態(tài)會(huì)被清除。
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
* 等待該線程死亡,最多等待millis毫秒。如果超時(shí)時(shí)間為0意味著永遠(yuǎn)等待。
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
* 此實(shí)現(xiàn)使用this.isAlive循環(huán)調(diào)用this.wait。
* 當(dāng)線程終止時(shí),調(diào)用this.notifyAll方法。
* 不建議應(yīng)用在Thread實(shí)例上使用 wait、notify、notifyAll。
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
* 如果任何線程中斷了該線程。當(dāng)異常拋出時(shí)當(dāng)前線程的interrupted狀態(tài)也將清除。
*/
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
yield方法
該方法就是說我讓出一下cpu的使用權(quán),但是我還是就緒狀態(tài),如果沒有其它競(jìng)爭(zhēng)者獲得CPU,
CPU的執(zhí)行權(quán)還是會(huì)給我,如果有其它競(jìng)爭(zhēng)者獲得CPU,那么就先讓它執(zhí)行。
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
* 向調(diào)度程序發(fā)出的提示,表示當(dāng)前線程愿意放棄處理器。調(diào)度程序可以隨意忽略此提示。
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
* Yield是一種啟發(fā)式嘗試,旨在改善線程之間的相對(duì)進(jìn)度,否則會(huì)過度使用CPU。
* 它的使用應(yīng)該與詳細(xì)的分析和基準(zhǔn)測(cè)試相結(jié)合,以確保它實(shí)際具有預(yù)期的效果。
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
* 很少適合使用該方法。它可能對(duì)調(diào)試或測(cè)試有用,因?yàn)樗赡苡兄谥噩F(xiàn)由于競(jìng)爭(zhēng)條件而產(chǎn)生的bug。
* 在設(shè)計(jì)諸如{@link java.util.concurrent.locks}包中的并發(fā)控制結(jié)構(gòu)時(shí),它可能也很有用。
* 在ReentrantLock的內(nèi)部類ConditionObject的transferAfterCancelledWait方法里就有使用。
*/
public static native void yield();
interrupt
- 線程阻塞在不同的地方,拋出的異常是不一樣的。
- 線程阻塞在不同的地方,中斷狀態(tài)有的清除有的不清除。
/**
* Interrupts this thread.
* 中斷該線程。
*
* <p> Unless the current thread is interrupting itself, which is
* always permitted, the {@link #checkAccess() checkAccess} method
* of this thread is invoked, which may cause a {@link
* SecurityException} to be thrown.
* 除非當(dāng)前線程中斷自身(這是始終允許的),否則將調(diào)用此線程的checkAccess方法,
* 這可能會(huì)導(dǎo)致拋出SecurityException。
*
* <p> If this thread is blocked in an invocation of the {@link
* Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
* Object#wait(long, int) wait(long, int)} methods of the {@link Object}
* class, or of the {@link #join()}, {@link #join(long)}, {@link
* #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
* methods of this class, then its interrupt status will be cleared and it
* will receive an {@link InterruptedException}.
* 如果在調(diào)用Object類的wait()、wait(long)或wait(long, int)方法時(shí)阻塞了該線程,
* 或者在該類的join()、join(long)、join(long, int)、sleep(long)、sleep(long, int)方法阻塞,
* 然后它的中斷狀態(tài)將被清除,它將收到一個(gè)InterruptedException。
*
* <p> If this thread is blocked in an I/O operation upon an {@link
* java.nio.channels.InterruptibleChannel InterruptibleChannel}
* then the channel will be closed, the thread's interrupt
* status will be set, and the thread will receive a {@link
* java.nio.channels.ClosedByInterruptException}.
* 如果此線程在java.nio.channels.interruptablechannel上的I/O操作中被阻塞,
* 然后通道將被關(guān)閉,線程的中斷狀態(tài)將被設(shè)置,線程將收到j(luò)ava.nio.channels.closedbyinteruptexception。
*
* <p> If this thread is blocked in a {@link java.nio.channels.Selector}
* then the thread's interrupt status will be set and it will return
* immediately from the selection operation, possibly with a non-zero
* value, just as if the selector's {@link
* java.nio.channels.Selector#wakeup wakeup} method were invoked.
* 如果該線程在ava.nio.channels.Selector中被阻塞,那么該線程的中斷狀態(tài)將被設(shè)置,
* 并且它將立即從選擇操作返回,可能帶有非零值,
* 就像調(diào)用了選擇器的java.nio.channels.Selector#wakeup方法一樣。
*
* <p> If none of the previous conditions hold then this thread's interrupt
* status will be set. </p>
* 如果前面的條件都不成立,那么將設(shè)置該線程的中斷狀態(tài)。
*
* <p> Interrupting a thread that is not alive need not have any effect.
* 中斷一個(gè)非活動(dòng)線程不需要有任何效果。
*
* @throws SecurityException
* if the current thread cannot modify this thread
*
* @revised 6.0
* @spec JSR-51
*/
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
* 測(cè)試線程是否已經(jīng)中斷。中斷狀態(tài)是否重置取決于傳遞的ClearInterrupted值。
*/
private native boolean isInterrupted(boolean ClearInterrupted);