自己寫一個線程池

public class MyThreadPool {
    private ArrayList<MyThread> threads;
    private ArrayBlockingQueue<Runnable> taskQueue; // tasks need to be executed
    private int threadNum;
    private int runningThreadNum;
    private final ReentrantLock lock = new ReentrantLock();

    public MyThreadPool(int initPoolNum) {
        this.threadNum = initPoolNum;
        this.threads = new ArrayList<>();
        this.taskQueue = new ArrayBlockingQueue<>(initPoolNum * 4);
        this.runningThreadNum = 0;
    }

    // runnable is a task
    public void execute(Runnable runnable) {
        try {
            this.lock.lock();
            if (runningThreadNum < threadNum) {
                MyThread myThread = new MyThread(runnable);
                myThread.start();
                threads.add(myThread);
                runningThreadNum++;
            } else {
                if (!taskQueue.offer(runnable)) {
                    System.out.println("Task queue is full");
                }
            }
        } finally {
            this.lock.unlock();
        }
    }

    class MyThread extends Thread {
        private Runnable task;

        public MyThread(Runnable runnable) {
            this.task = runnable;
        }

        public void run() {
            while (true) {
                // running task
                if (task != null) {
                    task.run();
                    task = null;
                } else {
                    Runnable tmpTask = taskQueue.poll();
                    if (tmpTask != null) {
                        tmpTask.run();
                    }

                }
            }
        }
    }

    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(30);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " running");
            }
        };
        for (int i = 0; i < 10; i++) {
            myThreadPool.execute(task);
        }
    }

}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容