socket編程3-ThreadPool

來源:互聯網
上載者:User

標籤:io   ar   os   sp   for   java   on   art   bs   

package Chapter3;

import java.util.LinkedList;

public class ThreadPool extends ThreadGroup {
    private boolean isClosed = false; // 線程池是否關閉
    private LinkedList<Runnable> workQueue; // 表示工作隊列,用來存放線程池要執行的任務,每個任務都是Runnable執行個體
    private static int threadPoolID; // 表示線程池ID
    private int threadID; // 表示背景工作執行緒ID

    public ThreadPool(int poolSize) { // poolSize指定線程池中的背景工作執行緒數目
        super("TheadPool-" + (threadPoolID++));
        setDaemon(true);
        workQueue = new LinkedList<Runnable>(); // 建立工作隊列
        for (int i = 0; i < poolSize; i++)
            new WorkThread().start(); // 建立並啟動背景工作執行緒
    }

    /** 向工作隊列中加入一個新的任務,由背景工作執行緒去執行該任務 */
    public synchronized void execute(Runnable task) {
        if (isClosed) {// 線程池被關閉則拋出IllegalStateException異常
            throw new IllegalStateException();
        }
        if (task != null) {
            workQueue.add(task);
            notify();// 喚醒正在getTask()方法中等待的背景工作執行緒
        }
    }

    /** 從工作隊列中取出一個任務,背景工作執行緒會調用此方法 */
    protected synchronized Runnable getTask() throws InterruptedException {
        while (workQueue.size() == 0) {
            if (isClosed)
                return null;
            wait();// 如果工作隊列中沒有任務,就等待任務
        }
        return workQueue.removeFirst();
    }

    /** 關閉線程池 */
    public synchronized void close() {
        if (!isClosed) {
            isClosed = true;
            workQueue.clear();// 清空工作隊列
            interrupt();// 中斷所有的背景工作執行緒,該方法繼承自ThreadGroup類
        }
    }

    /** 等待背景工作執行緒把所有任務執行完 */
    public void join() {
        synchronized (this) {
            isClosed = true;
            notifyAll();// 喚醒還在getTask()方法中等待任務的動作線程
        }
        Thread[] threads = new Thread[activeCount()];
        // enumerate()方法繼承自ThreadGroup類,獲得線程組中當前所有活著的背景工作執行緒
        int count = enumerate(threads);
        for (int i = 0; i < count; i++) {// 等待所有背景工作執行緒運行結束
            try {
                threads[i].join();// 等待背景工作執行緒運行結束
            } catch (InterruptedException ex) {
            }

        }

    }

    /** 內部類:背景工作執行緒 */
    private class WorkThread extends Thread {
        public WorkThread() {
            // 加入當前ThreadPool線程組中
            super(ThreadPool.this, "WorkThread-" + (threadID++));
        }

        public void run() {
            while (!isInterrupted()) {// isInterrupted()方法繼承自Thread類,判斷線程是否被中斷
                Runnable task = null;
                try {// 取出任務
                    task = getTask();
                } catch (InterruptedException ex) {
                }
                /**
                 * 如果getTask()返回null或線程執行getTask()時被中斷,則結束此線程
                 */
                if (task == null)
                    return;
                try {// 運行任務,異常在catch代碼塊中捕獲
                    task.run();
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }
    }
}

socket編程3-ThreadPool

聯繫我們

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