Java並發編程中使用Executors類建立和管理線程的用法_java

來源:互聯網
上載者:User

1. 類 Executors
Executors類可以看做一個“工具類”。援引JDK1.6 API中的介紹:
  此包中所定義的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 類的工廠和實用方法。此類支援以下各種方法:
(1)建立並返回設定有常用配置字串的 ExecutorService 的方法。
(2)建立並返回設定有常用配置字串的 ScheduledExecutorService 的方法。
(3)建立並返回“封裝的”ExecutorService 方法,它通過使特定於實現的方法不可訪問來禁用重新設定。
(4)建立並返回 ThreadFactory 的方法,它可將新建立的線程設定為已知的狀態。
(5)建立並返回非閉包形式的 Callable 的方法,這樣可將其用於需要 Callable 的執行方法中。
    通過這個類能夠獲得多種線程池的執行個體,例如可以調用newSingleThreadExecutor()獲得單線程的ExecutorService,調 用newFixedThreadPool()獲得固定大小線程池的ExecutorService,等等。拿到ExecutorService可以做的事情就比 較多了,最簡單的是用它來執行Runnable對象,也可以執行一些實現了Callable<T>的對象。用Thread的start()方 法沒有傳回值,如果該線程執行的方法有傳回值那用ExecutorService就再好不過了,可以選擇submit()、invokeAll()或者 invokeAny(),根據具體情況選擇合適的方法即可。
此類中提供的一些方法有:
1.1 public static ExecutorService newCachedThreadPool()
建立一個可根據需要建立新線程的線程池,但是在以前構造的線程可用時將重用它們。對於執行很多短期非同步任務的程式而言,這些線程池通常可提高程式效能。
 
1.2 public static ExecutorService newFixedThreadPool(int nThreads)
建立一個可重用固定線程數的線程池,以共用的無界隊列方式來運行這些線程。
 
1.3 public static ExecutorService newSingleThreadExecutor()
建立一個使用單個 worker 線程的 Executor,以無界隊列方式來運行該線程。
 
這三個方法都可以配合介面ThreadFactory的執行個體一起使用。並且返回一個ExecutorService介面的執行個體。
2. 介面 ThreadFactory
根據需要建立新線程的對象。使用線程工廠就無需再手工編寫對 new Thread 的調用了,從而允許應用程式使用特殊的線程子類、屬性等等。
此介面最簡單的實現就是:

class SimpleThreadFactory implements ThreadFactory {  public Thread newThread(Runnable r) {   return new Thread(r);  } }

3. 介面ExecutorService
該介面提供了管理終止的方法。
4.建立標準線程池啟動線程
4.1 提供一個簡單的實現Runnable介面的線程
MyThread.java

package com.zj.concurrency.executors; public class MyThread implements Runnable {  private int count = 1, number;   public MyThread(int num) {    number = num;    System.out.println("Create Thread-" + number);  }   public void run() {    while (true) {      System.out.println("Thread-" + number + " run " + count+" time(s)");      if (++count == 3)       return;    }  }}

這個線程會列印出相應的建立和執行資訊。
 
4.2使用CachedThreadPool啟動線程
CachedThreadPool.java

package com.zj.concurrency.executors;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; public class CachedThreadPool {  public static void main(String[] args) {    ExecutorService exec = Executors.newCachedThreadPool();    for (int i = 0; i < 5; i++)      exec.execute(new MyThread(i));    exec.shutdown();  }}

結果:

Create Thread-0Create Thread-1Create Thread-2Create Thread-3Thread-0 run 1 time(s)Thread-0 run 2 time(s)Thread-1 run 1 time(s)Thread-1 run 2 time(s)Thread-2 run 1 time(s)Thread-2 run 2 time(s)Create Thread-4Thread-4 run 1 time(s)Thread-4 run 2 time(s)Thread-3 run 1 time(s)Thread-3 run 2 time(s)

 
4.3 使用FixedThreadPool啟動線程

FixedThreadPool.javapackage com.zj.concurrency.executors;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; public class FixedThreadPool {  public static void main(String[] args) {    ExecutorService exec = Executors.newFixedThreadPool(2);    for (int i = 0; i < 5; i++)      exec.execute(new MyThread(i));    exec.shutdown();  }}

結果:

Create Thread-0Create Thread-1Create Thread-2Create Thread-3Create Thread-4Thread-0 run 1 time(s)Thread-0 run 2 time(s)Thread-2 run 1 time(s)Thread-2 run 2 time(s)Thread-3 run 1 time(s)Thread-3 run 2 time(s)Thread-4 run 1 time(s)Thread-4 run 2 time(s)Thread-1 run 1 time(s)Thread-1 run 2 time(s)

 
4.4 使用SingleThreadExecutor啟動線程
SingleThreadExecutor.java

package com.zj.concurrency.executors;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; public class SingleThreadExecutor {  public static void main(String[] args) {    ExecutorService exec = Executors.newSingleThreadExecutor();    for (int i = 0; i < 5; i++)      exec.execute(new MyThread(i));    exec.shutdown();  }}

結果:

Create Thread-0Create Thread-1Create Thread-2Create Thread-3Create Thread-4Thread-0 run 1 time(s)Thread-0 run 2 time(s)Thread-1 run 1 time(s)Thread-1 run 2 time(s)Thread-2 run 1 time(s)Thread-2 run 2 time(s)Thread-3 run 1 time(s)Thread-3 run 2 time(s)Thread-4 run 1 time(s)Thread-4 run 2 time(s)

5.配合ThreadFactory介面的使用
我們試圖給線程加入daemon和priority的屬性設定。
5.1設定後台線程屬性
DaemonThreadFactory.java

package com.zj.concurrency.executors.factory;import java.util.concurrent.ThreadFactory; public class DaemonThreadFactory implements ThreadFactory {  public Thread newThread(Runnable r) {    Thread t = new Thread(r);    t.setDaemon(true);    return t;  }}

 
5.2 設定優先權屬性
最高優先順序MaxPriorityThreadFactory.java

package com.zj.concurrency.executors.factory;import java.util.concurrent.ThreadFactory; public class MaxPriorityThreadFactory implements ThreadFactory {  public Thread newThread(Runnable r) {    Thread t = new Thread(r);    t.setPriority(Thread.MAX_PRIORITY);    return t;  }}

最低優先順序MinPriorityThreadFactory.java

package com.zj.concurrency.executors.factory;import java.util.concurrent.ThreadFactory; public class MinPriorityThreadFactory implements ThreadFactory {  public Thread newThread(Runnable r) {    Thread t = new Thread(r);    t.setPriority(Thread.MIN_PRIORITY);    return t;  }}

 
5.3啟動帶有屬性設定的線程
ExecFromFactory.java

package com.zj.concurrency.executors;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import com.zj.concurrency.executors.factory.DaemonThreadFactory;import com.zj.concurrency.executors.factory.MaxPriorityThreadFactory;import com.zj.concurrency.executors.factory.MinPriorityThreadFactory; public class ExecFromFactory {  public static void main(String[] args) throws Exception {    ExecutorService defaultExec = Executors.newCachedThreadPool();    ExecutorService daemonExec = Executors       .newCachedThreadPool(new DaemonThreadFactory());    ExecutorService maxPriorityExec = Executors       .newCachedThreadPool(new MaxPriorityThreadFactory());    ExecutorService minPriorityExec = Executors       .newCachedThreadPool(new MinPriorityThreadFactory());    for (int i = 0; i < 10; i++)      daemonExec.execute(new MyThread(i));    for (int i = 10; i < 20; i++)      if (i == 10)       maxPriorityExec.execute(new MyThread(i));      else if (i == 11)       minPriorityExec.execute(new MyThread(i));      else       defaultExec.execute(new MyThread(i));  }}

結果:

Create Thread-0Create Thread-1Create Thread-2Create Thread-3Thread-0 run 1 time(s)Thread-0 run 2 time(s)Thread-1 run 1 time(s)Thread-1 run 2 time(s)Thread-2 run 1 time(s)Thread-2 run 2 time(s)Create Thread-4Thread-4 run 1 time(s)Thread-4 run 2 time(s)Create Thread-5Thread-5 run 1 time(s)Thread-5 run 2 time(s)Create Thread-6Create Thread-7Thread-7 run 1 time(s)Thread-7 run 2 time(s)Create Thread-8Thread-8 run 1 time(s)Thread-8 run 2 time(s)Create Thread-9Create Thread-10Thread-10 run 1 time(s)Thread-10 run 2 time(s)Create Thread-11Thread-9 run 1 time(s)Thread-9 run 2 time(s)Thread-6 run 1 time(s)Thread-6 run 2 time(s)Thread-3 run 1 time(s)Thread-3 run 2 time(s)Create Thread-12Create Thread-13Create Thread-14Thread-12 run 1 time(s)Thread-12 run 2 time(s)Thread-13 run 1 time(s)Thread-13 run 2 time(s)Create Thread-15Thread-15 run 1 time(s)Thread-15 run 2 time(s)Create Thread-16Thread-16 run 1 time(s)Thread-16 run 2 time(s)Create Thread-17Create Thread-18Create Thread-19Thread-14 run 1 time(s)Thread-14 run 2 time(s)Thread-17 run 1 time(s)Thread-17 run 2 time(s)Thread-18 run 1 time(s)Thread-18 run 2 time(s)Thread-19 run 1 time(s)Thread-19 run 2 time(s)Thread-11 run 1 time(s)Thread-11 run 2 time(s)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.