本文最后更新于:星期四, 六月 18日 2020, 9:01 上午

来自《Java并发编程的艺术》

一个简易的线程池的实现。三个类:
ThreadPool线程池接口
DefaultThreadPool线程池接口实现
Worker工作线程

线程池的工作逻辑:
image.png

全部代码

package ConcurrencyArt;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

interface ThreadPool<Job extends Runnable> {
    void execute(Job job);//执行一个Job,这个Job需要实现Runnable

    void shutdown();//关闭线程池

    void addWorkers(int m);//增加工作者线程

    void removeWorkers(int m);//减少工作者线程

    int getJobSize();//得到正在等待执行的任务数量
}

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);
    }

    //初始化线程工作者
    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();
        }
    }

    @Override
    public void execute(Job job) {
        if (job != null) {
            synchronized (jobs) {
                jobs.addLast(job);
                jobs.notify();//在worker的run方法中的while循环中,调用了jobs.wait();
            }
        }
    }

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

    @Override
    public void addWorkers(int m) {
        synchronized (jobs) {
            if (m + this.workerNum > MAX_WORKER_NUMBERS) {
                m = MAX_WORKER_NUMBERS - this.workerNum;
            }
            initializeWorkers(m);
            this.workerNum += m;
        }
    }

    @Override
    public void removeWorkers(int m) {
        synchronized (jobs) {
            if (m >= this.workerNum) {
                throw new IllegalArgumentException("beyond workNum");
            }
            int count = 0;
            while (count < m) {
                Worker worker = workers.get(count);
                if (workers.remove(worker)) {
                    worker.shutdown();
                    count++;
                }
            }
            this.workerNum -= count;
        }
    }

    @Override
    public int getJobSize() {
        return jobs.size();
    }


    //工作者,负责消费任务。
    class Worker implements Runnable {
        private volatile boolean running = true;//在这里通过volatile boolean而不是interrupt方法来安全地中断线程

        @Override
        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    while (jobs.isEmpty()) {//当工作队列为空时,所有的工作者线程均等待在工作队列上。
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;//感知到外部对工作者线程的中断操作,返回。
                        }
                    }
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        //job,作为一个Runnable的实现类,在这里并未将其变成线程并start(),
                        // 而是将其的run方法放在工作者线程中执行,这样真正的多线程是指工作者线程,
                        //而提交进来的Job只是作为一个应该异步执行的任务。
                        job.run();
                    } catch (Exception ex) {
                        //忽略job执行中的exception
                    }
                }
            }
        }

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


java并发     

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!

Please-configure--Android-SDK 上一篇
Future相关类解释 下一篇