天天看點

定制并發類(五)在一個Executor對象中使用我們的ThreadFactory

在一個executor對象中使用我們的threadfactory

在前面的指南中,實作threadfactory接口生成自定義線程,我們引進了工廠模式和提供如何實作一個實作threadfactory接口的線程的工廠例子。

執行者架構(executor framework)是一種機制,它允許你将線程的建立與執行分離。它是基于executor、executorservice接口和實作這兩個接口的threadpoolexecutor類。它有一個内部的線程池和提供一些方法,這些方法允許你送出兩種任務給線程池執行。這兩種任務是:

實作runnable接口的類,用來實作沒有傳回結果的任務

實作callable接口的類,用來實作有傳回結果的任務

在執行者架構(executor framework)的内部,它提供一個threadfactory接口來建立線程,這是用來産生新的線程。在這個指南中,你将學習如何實作你自己的線程類,用一個工廠來建立這個類的線程,及如何在執行者中使用這個工廠,是以這個執行者将執行你的線程。

準備工作…

閱讀之前的指南,實作threadfactory接口生成自定義線程,并實作它的例子。

這個指南的例子使用eclipse ide實作。如果你使用eclipse或其他ide,如netbeans,打開它并建立一個新的java項目。

如何做…

按以下步驟來實作的這個例子:

1.将實作threadfactory接口生成自定義線程的指南中實作的mythread、mythreadfactory和mytask類複制到這個項目中,是以你将在這個例子中繼續使用它們。

2.實作這個例子的主類,通過建立main類,并實作mian()方法。

<code>1</code>

<code>public</code> <code>class</code> <code>main {</code>

<code>2</code>

<code>public</code> <code>static</code> <code>void</code> <code>main(string[] args)</code><code>throws</code> <code>exception {</code>

3.建立一個新的mythreadfactory對象,名為threadfactory。

<code>mythreadfactory threadfactory=</code><code>new</code> <code>mythreadfactory(</code><code>"mythreadfactory"</code><code>);</code>

4.使用executors類的newcachedthreadpool()方法,建立一個新的executor對象。傳入前面建立的工廠對象作為參數。這個新的executor對象将使用這個工廠建立必需的線程,是以它将執行mythread線程。

<code>executorservice executor=executors.newcachedthreadpool(threadfactory);</code>

5.建立一個新的task對象,并使用submit()方法将它送出給執行者。

<code>mytask task=</code><code>new</code> <code>mytask();</code>

<code>executor.submit(task);</code>

6.使用shutdown()方法關閉這個執行者。

<code>executor.shutdown();</code>

7.使用awaittermination()方法,等待執行者的結束。

<code>executor.awaittermination(</code><code>1</code><code>, timeunit.days);</code>

8.寫入一條資訊表明程式的結束。

<code>system.out.printf(</code><code>"main: end of the program.\n"</code><code>);</code>

它是如何工作的…

在前面指南(實作threadfactory接口生成自定義線程)中的它是如何工作的部分中,你可以閱讀到關于mythread、mythreadfactory和mytask工作的詳細解釋。

在這個例子的main()方法中,你已使用executors類的newcachedthreadpool()方法建立一個executor對象。你已傳入之前建立的工廠對象作為參數,是以已建立的executor對象将使用這個工廠來建立它所需的線程,并且它将執行mythread類的線程。

執行這個程式,你将看到關于線程的開始日期和它的執行時間的資訊。以下截圖顯示了這個例子産生的輸出:

定制并發類(五)在一個Executor對象中使用我們的ThreadFactory

參見

在第7章,定制并發類中的實作threadfactory接口生成自定義線程指南

繼續閱讀