建立Java線程池

來源:互聯網
上載者:User

線程池的作用:

線程池作用就是限制系統中執行線程的數量。
     根據系統的環境情況,可以自動或手動設定線程數量,達到啟動並執行最佳效果;少了浪費了系統資源,多了造成系統擁擠效率不高。用線程池控制線程數量,其他線程排隊等候。一個任務執行完畢,再從隊列的中取最前面的任務開始執行。若隊列中沒有等待進程,線程池的這一資源處於等待。當一個新任務需要運行時,如果線程池中有等待的背景工作執行緒,就可以開始運行了;否則進入等待隊列。

 

為什麼要用線程池:

  1. 減少了建立和銷毀線程的次數,每個背景工作執行緒都可以被重複利用,可執行多個任務
  2. 可以根據系統的承受能力,調整線程池中工作線線程的數目,防止因為因為消耗過多的記憶體,而把伺服器累趴下(每個線程需要大約1MB記憶體,線程開的越多,消耗的記憶體也就越大,最後死機)

線程池類

 

 

package com.tdt.impl.ls;import java.util.LinkedList;/** * @project LocationGateway * @author sunnylocus * @verson 1.0.0 * @date   Aug 2, 2008 * @jdk    1.4.2 */public class ThreadPool extends ThreadGroup {private boolean isClosed = false;  //線程池是否關閉 private LinkedList workQueue;      //工作隊列private static int threadPoolID = 1;  //線程池的idpublic ThreadPool(int poolSize) {  //poolSize 表示線程池中的背景工作執行緒的數量super(threadPoolID + "");      //指定ThreadGroup的名稱setDaemon(true);               //繼承到的方法,設定是否守護線程池workQueue = new LinkedList();  //建立工作隊列for(int i = 0; i < poolSize; i++) {new WorkThread(i).start();   //建立並啟動背景工作執行緒,線程池數量是多少就建立多少個背景工作執行緒}}/** 向工作隊列中加入一個新任務,由背景工作執行緒去執行該任務*/public synchronized void execute(Runnable task) {if(isClosed) {throw new IllegalStateException();}if(task != null) {workQueue.add(task);//向隊列中加入一個任務notify(); //喚醒一個正在getTask()方法中待任務的背景工作執行緒}}/** 從工作隊列中取出一個任務,背景工作執行緒會調用此方法*/private synchronized Runnable getTask(int threadid) throws InterruptedException {while(workQueue.size() == 0) {if(isClosed) return null;System.out.println("背景工作執行緒"+threadid+"等待任務...");wait();//如果工作隊列中沒有任務,就等待任務}System.out.println("背景工作執行緒"+threadid+"開始執行任務...");return (Runnable) workQueue.removeFirst(); //反回隊列中第一個元素,並從隊列中刪除}/** 關閉線程池 */public synchronized void closePool() {if(! isClosed) {waitFinish();        //等待背景工作執行緒執行完畢isClosed = true;workQueue.clear();  //清空工作隊列interrupt(); //中斷線程池中的所有的背景工作執行緒,此方法繼承自ThreadGroup類}}/** 等待背景工作執行緒把所有任務執行完畢*/public void waitFinish() {synchronized (this) {isClosed = true;notifyAll();//喚醒所有還在getTask()方法中等待任務的背景工作執行緒}Thread[] threads = new Thread[activeCount()]; //activeCount() 返回該線程組中活動線程的估計值。int count = enumerate(threads); //enumerate()方法繼承自ThreadGroup類,根據活動線程的估計值獲得線程組中當前所有活動的背景工作執行緒for(int i =0; i < count; i++) { //等待所有背景工作執行緒結束try {threads[i].join();//等待背景工作執行緒結束}catch(InterruptedException ex) {ex.printStackTrace();}}}/** * 內部類,背景工作執行緒,負責從工作隊列中取出任務,並執行 * @author sunnylocus */private class WorkThread extends Thread {private int id;public WorkThread(int id) {//父類構造方法,將線程加入到當前ThreadPool線程組中super(ThreadPool.this,id+"");this.id =id;}public void run() {while(! isInterrupted()) {  //isInterrupted()方法繼承自Thread類,判斷線程是否被中斷Runnable task = null;try {task = getTask(id);//取出任務}catch(InterruptedException ex) {ex.printStackTrace();}//如果getTask()返回null或者線程執行getTask()時被中斷,則結束此線程if(task == null) return;try {task.run();  //運行任務}catch(Throwable t) {t.printStackTrace();}}//  end while}//  end run}// end workThread}

 

2.測試類別

 

package com.tdt.test;import com.tdt.impl.ls.ThreadPool;public class ThreadPoolTest {public static void main(String[] args) throws InterruptedException {ThreadPool threadPool = new ThreadPool(3); //建立一個有個3背景工作執行緒的線程池Thread.sleep(500); //休眠500毫秒,以便讓線程池中的背景工作執行緒全部運行//運行任務for (int i = 0; i <=5 ; i++) { //建立6個任務threadPool.execute(createTask(i));}threadPool.waitFinish(); //等待所有任務執行完畢threadPool.closePool(); //關閉線程池}private static Runnable createTask(final int taskID) {return new Runnable() {public void run() {//System.out.println("Task" + taskID + "開始");System.out.println("Hello world");//System.out.println("Task" + taskID + "結束");}};}}

結果:

 

背景工作執行緒0等待任務...背景工作執行緒1等待任務...背景工作執行緒2等待任務...背景工作執行緒0開始執行任務...Hello world背景工作執行緒0等待任務...背景工作執行緒1開始執行任務...Hello world背景工作執行緒1等待任務...背景工作執行緒2開始執行任務...Hello world背景工作執行緒2等待任務...背景工作執行緒0開始執行任務...Hello world背景工作執行緒0等待任務...背景工作執行緒1開始執行任務...Hello world背景工作執行緒1等待任務...背景工作執行緒2開始執行任務...Hello world背景工作執行緒2等待任務...

 

聯繫我們

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