JAvaカスタムスレッドプールの実装

8906 ワード

JAvaカスタムスレッドプールの実装
スレッドプールインタフェースの定義
public interface ThreadPool<Job extends Runnable> {

    //     Job
    void execute(Job job);

    //      
    void shutdown();

    //        
    void addWorkers(int num);

    //        
    void removeWorker(int num);

    //              
    int getJobSize();
}

スレッドプールインタフェースのデフォルト実装
public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {

    //       
    private static int MAX_WORKER_NUMBERS = 10;

    //      
    private static int DEFAULT_WORKER_NUMBERS = 5;

    //       
    private static int MIN_WORKER_NUMBERS = 1;

    //     
    private final LinkedList jobs = new LinkedList<>();

    //      
    private final List 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();
            }
        }
    }

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

    @Override
    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;
        }
    }

    @Override
    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 jobs.size();
    }

    //           
    class Worker implements Runnable {

        //     
        private volatile boolean running = true;

        @Override
        public void run() {
            while (running) {
                Job job;
                synchronized (jobs) {
                    while (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            //       WorkerThread     ,  
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        job.run();
                    } catch (Exception ex) {
                        //  job      
                    }
                }

            }

        }

        public void shutdown() {

            running = false;

        }
    }
}

例「Java同時作成アート」4.4.3スレッドプール技術とその例