Java線程:新特徵-線程池

Java線程:新特徵-線程池
 
Sun在Java5中,對Java線程的類庫作了大量的擴展,其中線程池就是Java5的新特徵之一,除了線程池以外,還有不少多線程相關的內容,爲多線程的編程帶來了極大便利。爲了編寫高效穩定可靠的多線程程序,線程部分的新增內容顯得尤其重要。
 
有關Java5線程新特徵的內容所有在java.util.concurrent下面,裏面包含數目衆多的接口和類,熟悉這部分API特徵是一項艱難的學習過程。目前有關這方面的資料和書籍都少之又少,大所屬介紹線程方面書籍還停留在java5以前的知識層面上。
 
固然新特徵對作多線程程序沒有必須的關係,在java5以前通用能夠寫出很優秀的多線程程序。只是代價不同而已。
 
線程池的基本思想仍是一種對象池的思想,開闢一塊內存空間,裏面存放了衆多(未死亡)的線程,池中線程執行調度由池管理器來處理。當有線程任務時,從池中取一個,執行完成後線程對象歸池,這樣能夠避免反覆建立線程對象所帶來的性能開銷,節省了系統的資源。
 
在Java5以前,要實現一個線程池是至關有難度的,如今Java5爲咱們作好了一切,咱們只須要按照提供的API來使用,便可享受線程池帶來的極大便利。
 
Java5的線程池分好多種:固定尺寸的線程池、可變尺寸鏈接池、。
 
在使用線程池以前,必須知道如何去建立一個線程池,在Java5中,須要瞭解的是java.util.concurrent.Executors類的API,這個類提供大量建立鏈接池的靜態方法,是必須掌握的。
 
1、固定大小的線程池
 
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

/**
* Java線程:線程池-
*
* @author Administrator 2009-11-4 23:30:44
*/

public class Test {
         public static void main(String[] args) {
                 //建立一個可重用固定線程數的線程池
                ExecutorService pool = Executors.newFixedThreadPool(2);
                 //建立實現了Runnable接口對象,Thread對象固然也實現了Runnable接口
                Thread t1 = new MyThread();
                Thread t2 = new MyThread();
                Thread t3 = new MyThread();
                Thread t4 = new MyThread();
                Thread t5 = new MyThread();
                 //將線程放入池中進行執行
                pool.execute(t1);
                pool.execute(t2);
                pool.execute(t3);
                pool.execute(t4);
                pool.execute(t5);
                 //關閉線程池
                pool.shutdown();
        }
}

class MyThread extends Thread{
        @Override
         public void run() {
                System.out.println(Thread.currentThread().getName()+ "正在執行。。。");
        }
}
 
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。

Process finished with exit code 0
 
2、單任務線程池
 
在上例的基礎上改一行建立pool對象的代碼爲:
                 //建立一個使用單個 worker 線程的 Executor,以×××隊列方式來運行該線程。
                ExecutorService pool = Executors.newSingleThreadExecutor();
 
輸出結果爲:
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。

Process finished with exit code 0
 
對於以上兩種鏈接池,大小都是固定的,當要加入的池的線程(或者任務)超過池最大尺寸時候,則入此線程池須要排隊等待。
一旦池中有線程完畢,則排隊等待的某個線程會入池執行。
 
3、可變尺寸的線程池
 
與上面的相似,只是改動下pool的建立方式:
                 //建立一個可根據須要建立新線程的線程池,可是在之前構造的線程可用時將重用它們。
                ExecutorService pool = Executors.newCachedThreadPool();
 
pool-1-thread-5正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-4正在執行。。。
pool-1-thread-3正在執行。。。
pool-1-thread-2正在執行。。。

Process finished with exit code 0
 
4、延遲鏈接池
 
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
* Java線程:線程池-
*
* @author Administrator 2009-11-4 23:30:44
*/

public class Test {
         public static void main(String[] args) {
                 //建立一個線程池,它可安排在給定延遲後運行命令或者按期地執行。
                ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
                 //建立實現了Runnable接口對象,Thread對象固然也實現了Runnable接口
                Thread t1 = new MyThread();
                Thread t2 = new MyThread();
                Thread t3 = new MyThread();
                Thread t4 = new MyThread();
                Thread t5 = new MyThread();
                 //將線程放入池中進行執行
                pool.execute(t1);
                pool.execute(t2);
                pool.execute(t3);
                 //使用延遲執行風格的方法
                pool.schedule(t4, 10, TimeUnit.MILLISECONDS);
                pool.schedule(t5, 10, TimeUnit.MILLISECONDS);
                 //關閉線程池
                pool.shutdown();
        }
}

class MyThread extends Thread {
        @Override
         public void run() {
                System.out.println(Thread.currentThread().getName() + "正在執行。。。");
        }
}
 
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。

Process finished with exit code 0
 
5、單任務延遲鏈接池
 
在四代碼基礎上,作改動
                 //建立一個單線程執行程序,它可安排在給定延遲後運行命令或者按期地執行。
                ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
 
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-1正在執行。。。

Process finished with exit code 0
 
6、自定義線程池
 
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* Java線程:線程池-自定義線程池
*
* @author Administrator 2009-11-4 23:30:44
*/

public class Test {
         public static void main(String[] args) {
                 //建立等待隊列
                BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
                 //建立一個單線程執行程序,它可安排在給定延遲後運行命令或者按期地執行。
                ThreadPoolExecutor pool = new ThreadPoolExecutor(2,3,2,TimeUnit.MILLISECONDS,bqueue);
                 //建立實現了Runnable接口對象,Thread對象固然也實現了Runnable接口
                Thread t1 = new MyThread();
                Thread t2 = new MyThread();
                Thread t3 = new MyThread();
                Thread t4 = new MyThread();
                Thread t5 = new MyThread();
                Thread t6 = new MyThread();
                Thread t7 = new MyThread();
                 //將線程放入池中進行執行
                pool.execute(t1);
                pool.execute(t2);
                pool.execute(t3);
                pool.execute(t4);
                pool.execute(t5);
                pool.execute(t6);
                pool.execute(t7);
                 //關閉線程池
                pool.shutdown();
        }
}

class MyThread extends Thread {
        @Override
         public void run() {
                System.out.println(Thread.currentThread().getName() + "正在執行。。。");
                 try {
                        Thread.sleep(100L);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
        }
}
 
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。

Process finished with exit code 0
 
建立自定義線程池的構造方法不少,本例中參數的含義以下:

ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)
用給定的初始參數和默認的線程工廠及處理程序建立新的 ThreadPoolExecutor。使用 Executors 工廠方法之一比使用此通用構造方法方便得多。
參數:
corePoolSize - 池中所保存的線程數,包括空閒線程。
maximumPoolSize - 池中容許的最大線程數。
keepAliveTime - 當線程數大於核心時,此爲終止前多餘的空閒線程等待新任務的最長時間。
unit - keepAliveTime 參數的時間單位。
workQueue - 執行前用於保持任務的隊列。此隊列僅保持由 execute 方法提交的 Runnable 任務。
拋出:
IllegalArgumentException - 若是 corePoolSize 或 keepAliveTime 小於零,或者 maximumPoolSize 小於或等於零,或者 corePoolSize 大於 maximumPoolSize。
NullPointerException - 若是 workQueue 爲 null
 
自定義鏈接池稍微麻煩些,不過經過建立的ThreadPoolExecutor線程池對象,能夠獲取到當前線程池的尺寸、正在執行任務的線程數、工做隊列等等。
 
有關Java5線程池的內容到此就沒有了,更多的內容還須要研讀API來獲取。