天天看点

Java 用生产者消费者模型实现线程池

实际编码中经常遇到处理并发的场景,下面是一种用生产者-消费者模型实现的线程池,可以实现并发处理功能。

import java.util.LinkedList;
import java.util.Queue;

public class WorkerPool {

    // 线程池Worker数量
    private static final int WORKER_COUNT = 10;
    
    // 任务队列
    private Queue<String> queue = new LinkedList<String>();
    
    // 工作线程池
    private Thread[] threadPool = new WorkerThread[WORKER_COUNT];
    
    public WorkerPool() {
        for (Thread worker : threadPool) {
            worker = new WorkerThread(this);
            worker.start();
        }
    }
    
    // 接收请求
    public void assign(String request) {
        synchronized (queue) {
            if (queue.offer(request)) {
                queue.notify();
            } else {
                System.out.println("Push request to queue failed.");
            }
        }
    }
    
    // 等待请求
    public String await() {
        while (true) {
            synchronized (queue) {
                while (queue.size() == 0) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return queue.poll();
            }
        }
    }
    
    // 工作线程类
    private class WorkerThread extends Thread {
        private WorkerPool workerPool;
        
        public WorkerThread(WorkerPool workerPool) {
            this.workerPool = workerPool;
        }
        
        @Override
        public void run() {
            while (true) {
                String request = workerPool.await();
                System.out.println("正在处理请求:" + request);
            }
        }
    }
    
    public static void main(String[] args) {
        WorkerPool workerPool = new WorkerPool();
        workerPool.assign("New request");
    }
}
           

也可以不使用wait(),notify(),而是直接用BlockingQueue来实现。

参考文章:

http://www.cnblogs.com/dolphin0520/p/3920385.html