本文目錄一覽:
java獲得當前線程有兩種方法,第一種是Thread.currentThread();誰知道另外一種?
另外一種是實現Runnable介面,implements Runnable
這種方法有兩個好處是
(1)適合多個相同程序代碼的線程去處理同一資源的情況,把虛擬CPU(線程)同程序的代碼,數據有效的分離,較好地體現了面向對象的設計思想。
(2)可以避免由於Java的單繼承特性帶來的局限。經常碰到這樣一種情況,即當要將已經繼承了某一個類的子類放入多線程中,由於一個類不能同時有兩個父類,所以不能用繼承Thread類的方式,那麼,這個類就只能採用實現Runnable介面的方式了。
java獲取當前線程狀態。
java線程的狀態有下面幾種狀態:
/**
* 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
*
* pA thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called ttObject.wait()/tt
* on an object is waiting for another thread to call
* ttObject.notify()/tt or ttObject.notifyAll()/tt on
* that object. A thread that has called ttThread.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;
java 如何獲得線程池中正在執行的線程數
java中線程池的監控可以檢測到正在執行的線程數。
通過線程池提供的參數進行監控。線程池裡有一些屬性在監控線程池的時候可以使用
taskCount:線程池需要執行的任務數量。
completedTaskCount:線程池在運行過程中已完成的任務數量。小於或等於taskCount。
largestPoolSize:線程池曾經創建過的最大線程數量。通過這個數據可以知道線程池是否滿過。如等於線程池的最大大小,則表示線程池曾經滿了。
getPoolSize:線程池的線程數量。如果線程池不銷毀的話,池裡的線程不會自動銷毀,所以這個大小隻增不+
getActiveCount:獲取活動的線程數。
通過擴展線程池進行監控。通過繼承線程池並重寫線程池的beforeExecute,afterExecute和terminated方法,我們可以在任務執行前,執行後和線程池關閉前干一些事情。如監控任務的平均執行時間,最大執行時間和最小執行時間等。這幾個方法在線程池裡是空方法。如:
protected
void
beforeExecute(Thread
t,
Runnable
r)
{
}
原創文章,作者:WQTR,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/134724.html