【從0到1學習Java線程池】一個Java線程池的簡單實現

這是【從0到1學習Java線程池】系列文章的第 叄 篇,該系列文章總共三篇,介紹了 Java 線程池的使用以及原理,並且最後會實現一個基本的線程池。本篇文章實現了一個簡單的 Java 線程池。

【從0到1學習Java線程池】系列文章共有3篇,目錄如下:

從上兩篇文章中,我們已經知道了線程池的基本原理,這篇文章我們就來具體實現一個簡單的 Java 線程池。

設計先行

想要實現一個線程池,我們首先要來進行設計,考慮它需要有哪些功能,如何設計和安排這些功能是至關重要的。

在我們所要實現的 Java 線程池需要有:

  • 任務隊列:它能夠添加或者刪除任務,並且它還需要支持原子操作,不能同時有多個線程從中取出任務。
  • 通知機制:如果任務隊列爲空,工作線程將會阻塞在獲取任務這一操作上;如果這時任務隊列中有了新的任務,需要通知工作線程從中獲取任務來執行。
  • 線程類:線程類的例程是用來獲取任務和執行任務的。
  • 任務類:用於被線程抓取和執行的任務。
  • 線程管理類:能夠創建一定數量的線程,並且提供對任務隊列進行操作的方法(獲取任務、添加任務等)。

具體實現

系統配置類

其中的參數主要是該線程池所支持的最大線程數

public class SystemConfig {
    static final int THREAD_POOL_MAX_SIZE = 20;

    public static int getThreadDefalutSize(){
        return THREAD_POOL_MAX_SIZE;
    }
}

任務類

public class Task implements Runnable {
    @Override
    public void run() {

    }
}

線程管理類

public class ThreadPoolManager extends ThreadGroup {
    int isThreadPoolValid = 0;

    int sizeOfPoolThread = SystemConfig.getThreadDefalutSize();

    List<Task> taskList= new LinkedList<Task>();


    public ThreadPoolManager(String threadpoolname) {
        super(threadpoolname);
        setDaemon(true);
    }

    public synchronized void startThreadPool(){
        if(sizeOfPoolThread == 0 || isThreadPoolValid != 0){
            try{
                throw new Exception();
            }
            catch(Exception exception){
                exception.printStackTrace();
            }
            return;
        }
        if(taskList == null){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        for(int i = 0; i < sizeOfPoolThread; i++){
            new WorkThread(i).start();
        }

        isThreadPoolValid = 1;
    }

    public synchronized void stopThreadPool(){
        if(sizeOfPoolThread == 0 || isThreadPoolValid != 0){
            try{
                throw new Exception();
            }
            catch(Exception exception){
                exception.printStackTrace();
            }
            return;
        }
        if(taskList == null){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        taskList.clear();
        sizeOfPoolThread = 0;
        isThreadPoolValid = 0;
        interrupt();
    }

    public synchronized void addTask(Task newTask){
        if(taskList == null){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        taskList.add(newTask);

        notify();
    }

    public synchronized Task getTask(){
        if(taskList == null){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        while(taskList.size() == 0){
            try{
                wait();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return taskList.remove(0);

    }

    private class WorkThread extends Thread{
        public WorkThread(int threadID){
            super(ThreadPoolManager.this, ""+threadID);
        }

        public void run(){
            while(!isInterrupted()){
                Task runTask = getTask();

                if(runTask == null)
                    break;
                runTask.run();
            }
        }
    }
}

運行測試

測試代碼

測試任務

public class TestTask extends Task {
    private int i;

    public TestTask(int i){
        this.i = i;
    }

    public void run(){
        System.out.println("Task " + i + " is RUNNING.");
    }
}

主程序

public class ThreadPoolTest {
    public static void main(String[] args) {
        ThreadPoolManager manager = new ThreadPoolManager("SimplePool");
        manager.startThreadPool();

        for(int i = 0; i < 5; i++){
            Task task = new TestTask(i);
            manager.addTask(task);
        }
    }
}

測試結果

Task 3 is RUNNING.
Task 4 is RUNNING.
Task 1 is RUNNING.
Task 0 is RUNNING.
Task 2 is RUNNING.

本文的版權歸作者 羅遠航 所有,採用 Attribution-NonCommercial 3.0 License。任何人可以進行轉載、分享,但不可在未經允許的情況下用於商業用途。

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