1. 程式人生 > >《 Java併發程式設計從入門到精通》 Java執行緒池的監控

《 Java併發程式設計從入門到精通》 Java執行緒池的監控

9.1 Java執行緒池的監控

如果想實現執行緒池的監控,必須要自定義執行緒池繼承ThreadPoolExecutor類,並且實現beforeExecute,afterExecute和terminated方法,我們可以在任務執行前,執行後和執行緒池關閉前幹一些事情。如監控任務的平均執行時間,最大執行時間和最小執行時間等。這幾個方法線上程池裡是空方法。如:

//每執行一個工作任務執行緒之前都會執行此實現的方法

protected void beforeExecute(Thread t, Runnable r) {

//t – 放線上程池裡面要執行的執行緒。
//r – 將要執行這個執行緒的執行緒池裡面的工作執行緒。

}

//每執行一個工作任務執行緒之後都會執行的方法

protected void afterExecute(Runnable r, Throwable t) {

//r – 已經執行結束的工作執行緒。
//t – 執行異常。

}

//執行緒池關閉之前可以幹一些事情;

protected void terminated() { };

執行緒池裡有一些屬性在監控執行緒池的時候可以使用: 

  1. taskCount:執行緒池需要執行的任務數量。
  2. completedTaskCount:執行緒池在執行過程中已完成的任務數量。小於或等於taskCount。
  3. largestPoolSize:執行緒池曾經建立過的最大執行緒數量。通過這個資料可以知道執行緒池是否滿過。如等於執行緒池的最大大小,則表示執行緒池曾經滿了。
  4. getPoolSize:執行緒池的執行緒數量。如果執行緒池不銷燬的話,池裡的執行緒不會自動銷燬,所以這個大小隻增不+
  5. getActiveCount:獲取活動的執行緒數。

大家想一想如果你來寫的話如何去寫,提供例項demo如下,慢慢體會一下:

public class MonitorThreadPoolExecutorDemo {

public static void main(String[] args) throws InterruptedException, ExecutionException {

Thread. sleep(500L);// 方便測試

ExecutorService executor = new

 MonitorThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS , new LinkedBlockingQueue() );

for (int i = 0; i < 3; i++) {

Runnable runnable = new Runnable() {

public void run() {

try {

Thread. sleep(100L);

catch (InterruptedException e) {

e.printStackTrace();

}

}

};

executor.execute(runnable);

}

executor.shutdown();

System. out.println(“Thread Main End!” );

}

}

class MonitorThreadPoolExecutor extends ThreadPoolExecutor {

public MonitorThreadPoolExecutor(int arg0, int arg1, long arg2, TimeUnit arg3, BlockingQueue<Runnable> arg4) {

super(arg0, arg1, arg2, arg3, arg4);

}

protected void beforeExecute(Thread paramThread, Runnable paramRunnable) {

System. out.println(“work_task before:” + paramThread.getName());

}

protected void afterExecute(Runnable r, Throwable t) {

super.afterExecute(r, t);

System. out.println(“work_task after worker thread is :” + r);

}

protected void terminated() {

System. out.println(“terminated getCorePoolSize:” + this.getCorePoolSize() + “;getPoolSize:” + this.getPoolSize() + “;getTaskCount:” + this .getTaskCount() + “;getCompletedTaskCount:”

this.getCompletedTaskCount() + “;getLargestPoolSize:” + this.getLargestPoolSize() + “;getActiveCount:” + this.getActiveCount());

System. out.println(“ThreadPoolExecutor terminated:” );

}

}

執行結果如下:

work_task before:pool-1-thread-1

work_task before:pool-1-thread-3

work_task before:pool-1-thread-2

Thread Main End!

work_task after worker thread is :[email protected]

work_task after worker thread is :[email protected]

work_task after worker thread is :[email protected]

terminated getCorePoolSize:5;getPoolSize:0;getTaskCount:3;getCompletedTaskCount:3;getLargestPoolSize:3;getActiveCount:0

ThreadPoolExecutor terminated: