Java动态线程池

时间:2019-06-20 08:26:01

标签: java multithreading java-threads thread-synchronization

我想用Java编写一个线程池,它会自动调整其工作者的数量。无需动态调整大小即可,这很容易,如下面的示例类所示。

我认为,每当一个任务入队时,我都应该检查是否需要添加一个工作器。每次工人完成任务时,都应检查是否有多余的工人。

public class ThreadPool {

private static final int WORKER_THREADS = 5;
private static final int MIN_WORKER_THREADS = 2;

private List<Thread> worker;
private LinkedList<ThreadTask> queue;


public ThreadPool() {
    this.worker = new ArrayList<Thread>();
    this.queue = new LinkedList<ThreadTask>();

    for (int i = 0; i < WORKER_THREADS; i++) {
        addThread();
    }
}

private void addThread() {
    WorkerThread thread = new WorkerThread();
    thread.start();
    this.worker.add(thread);
}

public void enque(ThreadTask task) {
    synchronized (queue) {
        queue.add(task);

        // ADD WORKER HERE 

        queue.notify();
    }
}

private class WorkerThread extends Thread {

    @Override
    public void run() {
        while (true) {
            ThreadTask task;
            synchronized (queue) {
                while (queue.isEmpty()) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {

                    }
                }
                task = queue.poll();
            }
            try {
                task.run();
                // REMOVE WORKER HERE
            } catch (RuntimeException rte) {

            }
        }
    }
}

但是说实话,我不确定什么以及如何进行同步。我的第一个猜测是同步workerThreads列表,但这实际上根本不起作用。

请不要问我为什么要编写自定义ThreadPool-仅出于学习和演示目的。

谢谢。

0 个答案:

没有答案
相关问题