实际编码中经常遇到处理并发的场景,下面是一种用生产者-消费者模型实现的线程池,可以实现并发处理功能。
也可以不使用wait(),notify(),而是直接用BlockingQueue来实现。
import java.util.LinkedList;
import java.util.Queue;
public class WorkerPool {
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");
}
}
https://blog.csdn.net/sword_out/article/details/51517886
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)