人力资源管理系统。您可以创建BlockingQueue<Runnable>
具有固定容量的 a 并让每个工作线程出列 aRunnable
并运行它。然后你可以有一个生产者线程,它将作业放入队列。
主线程会做类似的事情:
// 100 is the capacity of the queue before blocking
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(100);
// start the submitter thread
new Thread(new JobSubmitterThread(queue)).start();
// make in a loop or something?
new Thread(new WorkerThread(queue)).start();
new Thread(new WorkerThread(queue)).start();
...
工人看起来像:
public class WorkerThread implements Runnable {
private final BlockingQueue<Runnable> queue;
public WorkerThread(BlockingQueue<Runnable> queue) {
this.queue = queue;
}
public void run() {
// run until the main thread shuts it down using volatile boolean or ...
while (!shutdown) {
Runnable job = queue.take();
job.run();
}
}
}
作业提交者看起来像:
public class JobSubmitterThread implements Runnable {
private final BlockingQueue<Runnable> queue;
public WorkerThread(BlockingQueue<Runnable> queue) {
this.queue = queue;
}
public void run() {
for (int jobC = 0; jobC < 1000; jobC++) {
Runnable job = makeJob();
// this would block when the queue reaches capacity
queue.put(job);
}
}
}