Java並發編程 - Executor架構(一)Executor,

來源:互聯網
上載者:User

標籤:his   rect   class   scheduled   void   cte   finally   實現   lex   

1、並發編程的一種編程方式是把任務拆分為一些列的小任務,即Runnable,然後將這些任務提交給一個Executor執行, Executor.execute(Runnalbe) 。Executor在執行時使用其內部的線程池來完成操作。

Executor的子介面有:ExecutorService,ScheduledExecutorService,已知實作類別:AbstractExecutorService,ScheduledThreadPoolExecutor,ThreadPoolExecutor。

2、Executor屬於public類型的介面。可以用於提交,管理或者執行Runnable任務。實現Executor介面的class還可以控制Runnable任務執行線程的具體細節。包括線程使用的細節、調度等。一般來說,Runnable任務開闢在新線程中的使用方法為:new Thread(new (RunnableTask())).start()

3、但在Executor中,可以使用Executor而不用顯示地建立線程。例如,可以使用以下方法建立線程,而不是像第2點中為一種任務中的每個任務都調用new Thread(...)的方法。

Exectuor executor = anExecutor();executor.execute(new RunnableTask()); // 非同步執行executor.execute(new RunnableTask());

4、但是,Executor介面並沒有嚴格地要求執行必須是非同步/同步的,一切都相當自由。在最簡單的情況下,執行程式可以在調用者的線程中立即運行已提交的任務,

class DirectExecutor implements Executor { public void execute(Runnable r) {r.run(); }}

更常見的是,任務在某個不是調用者線程的線程中執行的。如在另一個線程中啟動:

class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) {new Thread(r).start();}}

也可以在實現中用另一個Executor來序列化執行過程:

class SerialExecutor implements Executor {final Queue<Runnable> tasks = new ArrayDeque<Runnable>();final Executor executor;Runnable active;SerialExecutor(Executor executor) {this.executor = executor;}public synchronized void execute(final Runnable r) {tasks.offer(new Runnable() {public void run() {try {r.run();} finally {scheduleNext();}}});if (active == null) {scheduleNext();}}protected synchronized void scheduleNext() {if ((active = tasks.poll()) != null) {executor.execute(active);}}}

5、ThreadPoolExecutor類提供了一個可供可擴充的線程池實現。Executors類為Executor介面及其實現提供了便捷的Factory 方法。

6、 Executor中的方法execute。void execute(Runnable command)表示在未來的某個時間執行給定的命令。該命令可能在新的線程、已經入池的線程或者正在調用的線程中執行。



Java並發編程 - Executor架構(一)Executor,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.