3 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
你應(yīng)該好好JDK
關(guān)于線程狀態(tài)的文檔java.lang.Thread.State
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;
}
RUNNABLE
狀態(tài)指的是,線程正在JVM
中運(yùn)行,但是它們需要等待來自操作系統(tǒng)的資源
,比如說CPU
資源,這里當(dāng)然是網(wǎng)絡(luò)資源,所以它本該就是RUNNABLE
的。BLOCKED
狀態(tài),專門指的是線程正在等待內(nèi)置鎖的過程。WAITING
說明線程正在等待另一個(gè)線程的特定操作。
想要結(jié)束這種等待,要么給與線程所需要的網(wǎng)絡(luò)資源(這種控制不了),要么直接關(guān)閉Socket
,或者調(diào)用interrupt
方法(其實(shí)底層也是關(guān)閉Socket
,可以看看interrupt
的API
文檔)。

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
我覺得設(shè)置 socket 的超時(shí)時(shí)間比較合適, 如
socket = new Socket(IP, PORT);
socket.setSoTimeout(1000 * 60); // 讀操作的超時(shí)時(shí)間為 60 秒
如此, 當(dāng) socket read 在超過 60秒沒有收到數(shù)據(jù)時(shí), 將拋出 SocketException 異常.
另外, 在 try finally 中應(yīng)釋放資源(關(guān)閉 socket).
添加回答
舉報(bào)