一個線程池的簡單實現


 

原理:

核心構成: 1.任務(Runnable對象)  2. 一個阻塞隊列   3.多個工作線程

1. 將實現了Runnable接口的類對象 作爲任務 放到  阻塞隊列

2. 阻塞隊列作爲生產者, 線程列表作爲消費者 ,列表中的每個線程消費隊列中的任務, 沒有任務了則阻塞等待。

 

代碼:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {

    /** 利用阻塞隊列實現生產者-消費者模式 */
    BlockingQueue<Runnable> workQueue;

    /** 工作線程 */
    MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;
        for (int i = 0; i < poolSize; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
        }
    }

    void execute(Runnable command) {
        // 放入任務,如果沒有空間,則阻塞等待
        try {
            workQueue.put(command);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class WorkThread extends Thread {
        @Override
        public void run() {
            // 循環取任務並執行
            while (true) {
                Runnable task = null;
                // 獲取阻塞隊列的第一個任務,並刪除
                // 如果沒有元素,則會阻塞等待
                try {
                    task = workQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印當前線程
                System.out.print(this);
                task.run();
            }
        }
    }

    public static void main(String[] args) {
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(5);
        //初始化線程池
        MyThreadPool pool = new MyThreadPool(2, workQueue);
        for (int i = 0; i < 10; i++) {
            int num = i;
            //參數是是一個實現了Runnable接口的類的對象  是以匿名內部類的方式創建, 匿名內部類僅限於只實例化一次的內部類,優點就是簡潔
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任務 " + num + " 執行");
                }
            });
        }
    }

}

相關:

https://bbs.csdn.net/topics/390931316

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章