透過簡單示例瞭解執行緒池實現原理

神圣兽国窝窝乡独行侠發表於2024-10-12
public interface ThreadPool<Job extends Runnable> {
    // 執行一個Job,這個Job需要實現Runnable
    void execute(Job job);

    // 關閉執行緒池
    void shutdown();

    // 增加工作者執行緒
    void addWorkers(int num);

    // 減少工作者執行緒
    void removeWorker(int num);

    // 得到正在等待執行的任務數量
    int getJobSize();
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 預設執行緒池
 *
 * @param <Job>
 */
public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
    // 執行緒池最大限制數
    private static final int MAX_WORKER_NUMBERS = 10;

    // 執行緒池預設的數量
    private static final int DEFAULT_WORKER_NUMBERS = 5;

    // 執行緒池最小的數量
    private static final int MIN_WORKER_NUMBERS = 1;

    // 這是一個工作列表,將會向裡面插入工作
    private final LinkedList<Job> jobs = new LinkedList<>();

    // 工作者列表
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<>());

    // 工作者執行緒的數量
    private int workerNum = DEFAULT_WORKER_NUMBERS;

    // 執行緒編號生成
    private AtomicLong threadNum = new AtomicLong();

    public DefaultThreadPool() {
        initializeWorkers(DEFAULT_WORKER_NUMBERS);
    }

    public DefaultThreadPool(int num) {
        workerNum = num > MAX_WORKER_NUMBERS ? MAX_WORKER_NUMBERS : num < MIN_WORKER_NUMBERS ? MIN_WORKER_NUMBERS : num;
        initializeWorkers(workerNum);
    }

    @Override
    public void execute(Job job) {
        if (job != null) {
            // 新增一個工作,然後進行通知
            synchronized (jobs) {
                jobs.addLast(job);
                jobs.notify();
            }
        }
    }

    public void shutdown() {
        for (Worker worker : workers) {
            worker.shutdown();
        }
    }

    public void addWorkers(int num) {
        synchronized (jobs) {
            // 限制新增的Worker數量不能超過最大值
            if (num + this.workerNum > MAX_WORKER_NUMBERS) {
                num = MAX_WORKER_NUMBERS - this.workerNum;
            }
            initializeWorkers(num);
            this.workerNum += num;
        }
    }

    public void removeWorker(int num) {
        synchronized (jobs) {
            if (num >= this.workerNum) {
                throw new IllegalArgumentException("beyond workNum");
            }
            // 按照給定的數量停止Worker
            int count = 0;
            while (count < num) {
                Worker worker = workers.get(count);
                if (workers.remove(worker)) {
                    worker.shutdown();
                    count++;
                }
            }
            this.workerNum -= count;
        }
    }


    @Override
    public int getJobSize() {
        return 0;
    }

    // 初始化執行緒工作者
    private void initializeWorkers(int num) {
        for (int i = 0; i < num; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread thread = new Thread(worker, "ThreadPool-Worker-" + threadNum.incrementAndGet());
            thread.start();
        }
    }

    class Worker implements Runnable {
        private volatile boolean running = true;

        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    // 如果工作者列表是空的,那麼就wait
                    while (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException ex) {
                            // 感知到外部對WorkerThread的中斷操作,返回
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    // 取出一個Job
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        job.run();
                    } catch (Exception ex) {
                        // 忽略Job執行中的Exception
                    }
                }
            }
        }

        public void shutdown() {
            running = false;
        }
    }
}

相關文章