26、Java並發性和多線程-線程池

來源:互聯網
上載者:User

標籤:自己的   tee   public   閱讀   star   epo   logs   .com   入隊   

以下內容轉自http://ifeve.com/thread-pools/:

線程池(Thread Pool)對於限制應用程式中同一時刻啟動並執行線程數很有用。因為每啟動一個新線程都會有相應的效能開銷,每個線程都需要給棧分配一些記憶體等等。

我們可以把並發執行的任務傳遞給一個線程池,來替代為每個並發執行的任務都啟動一個新的線程。只要池裡有閒置線程,任務就會分配給一個線程執行。線上程池的內部,任務被插入一個阻塞隊列(Blocking Queue ),線程池裡的線程會去取這個隊列裡的任務。當一個新任務插入隊列時,一個空閑線程就會成功的從隊列中取出任務並且執行它。

線程池經常應用在多線程伺服器上。每個通過網路到達伺服器的串連都被封裝成一個任務並且傳遞給線程池。線程池的線程會並發的處理串連上的請求。以後會再深入有關Java實現多線程伺服器的細節。

Java 5在java.util.concurrent包中內建了內建的線程池,所以你不用非得實現自己的線程池。你可以閱讀我寫的java.util.concurrent.ExecutorService的文章以瞭解更多有關內建線程池的知識。不過無論如何,知道一點關於線程池實現的知識總是有用的。

這裡有一個簡單的線程池實現:

public class ThreadPool {    private BlockingQueue taskQueue = null;    private List<PoolThread> threads = new ArrayList<PoolThread>();    private boolean isStopped = false;    public ThreadPool(int noOfThreads, int maxNoOfTasks){        taskQueue = new BlockingQueue(maxNoOfTasks);        for(int i=0; i<noOfThreads; i++){            threads.add(new PoolThread(taskQueue));        }        for(PoolThread thread : threads){            thread.start();        }    }    public synchronized void  execute(Runnable task) throws Exception{        if(this.isStopped) throw            new IllegalStateException("ThreadPool is stopped");        this.taskQueue.enqueue(task);    }    public synchronized void stop(){        this.isStopped = true;        for(PoolThread thread : threads){           thread.doStop();        }    }}public class PoolThread extends Thread {    private BlockingQueue taskQueue = null;    private boolean       isStopped = false;    public PoolThread(BlockingQueue queue){        taskQueue = queue;    }    public void run(){        while(!isStopped()){            try{                Runnable runnable = (Runnable) taskQueue.dequeue();                runnable.run();            } catch(Exception e){                //log or otherwise report exception,                //but keep pool thread alive.            }        }    }    public synchronized void doStop(){        isStopped = true;        this.interrupt(); //break pool thread out of dequeue() call.    }    public synchronized boolean isStopped(){        return isStopped;    }}

(校註:原文有編譯錯誤,我修改了下)

public class PoolThread extends Thread {  private BlockingQueue<Runnable> taskQueue = null;  private boolean       isStopped = false;  public PoolThread(BlockingQueue<Runnable> queue) {    taskQueue = queue;  }  public void run() {    while (!isStopped()) {      try {        Runnable runnable =taskQueue.take();        runnable.run();      } catch(Exception e) {        // 寫日誌或者報告異常,        // 但保持線程池運行.      }    }  }  public synchronized void toStop() {    isStopped = true;    this.interrupt(); // 打斷池中線程的 dequeue() 調用.  }  public synchronized boolean isStopped() {    return isStopped;  }}

線程池的實現由兩部分組成。類ThreadPool是線程池的公開介面,而類PoolThread用來實現執行任務的子線程。

為了執行一個任務,方法ThreadPool.execute(Runnable r)用Runnable的實現作為調用參數。在內部,Runnable對象被放入阻塞隊列 (Blocking Queue),等待著被子線程取出隊列。

一個閒置PoolThread線程會把Runnable對象從隊列中取出並執行。你可以在PoolThread.run()方法裡看到這些代碼。執行完畢後,PoolThread進入迴圈並且嘗試從隊列中再取出一個任務,直到線程終止。

調用ThreadPool.stop()方法可以停止ThreadPool。在內部,調用stop先會標記isStopped成員變數(為 true)。然後,線程池的每一個子線程都調用PoolThread.stop()方法停止運行。注意,如果線程池的execute()在stop()之後調用,execute()方法會拋出IllegalStateException異常。

子線程會在完成當前執行的任務後停止。注意PoolThread.stop()方法中調用了this.interrupt()。它確保阻塞在taskQueue.dequeue()裡的wait()調用的線程能夠跳出wait()調用(校對註:因為執行了中斷interrupt,它能夠打斷這個調用),並且拋出一個InterruptedException異常離開dequeue()方法。這個異常在PoolThread.run()方法中被截獲、報告,然後再檢查isStopped變數。由於isStopped的值是true, 因此PoolThread.run()方法退出,子線程終止。

(校對註:看完覺得不過癮?更詳細的線程池文章參見Java線程池的分析和使用)

26、Java並發性和多線程-線程池

聯繫我們

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