【发布时间】:2012-09-27 11:26:29
【问题描述】:
我必须做功课,我已经完成了一些代码,但有一些问题:
必须在 java 中创建一个 boss-workers 应用程序。
- 我有这些课程:
Main WorkerThread BossThread Job
基本上我想做的是,BossThread 持有一个BlockingQueue,工人去那里寻找Jobs。
问题 1:
目前我开始 5 WorkingThreads 和 1 BossThread。
主要:
Collection<WorkerThread> workers = new ArrayList<WorkerThread>();
for(int i = 1; i < 5; i++) {
WorkerThread worker = new WorkerThread();
workers.add(worker);
}
BossThread thread = new BossThread(jobs, workers);
thread.run();
老板线程:
private BlockingQueue<Job> queue = new ArrayBlockingQueue<Job>(100);
private Collection<WorkerThread> workers;
public BossThread(Set<Job> jobs, Collection<WorkerThread> workers) {
for(Job job : jobs) {
queue.add(job);
}
for(WorkerThread worker : workers) {
worker.setQueue(queue);
}
this.workers = workers;
}
这是正常的,还是我应该在我的BossThread 中创建WorkerThreads?
问题 2:
如您所见,我将队列分配给每个 WorkerThread ,这是合理的还是我只能将队列存储在一个地方?
问题 3:
我必须让我的BossThread 以某种方式运行,只是为了等待用户是否将更多内容添加到队列中?以及我如何保持WorkerThreads 运行以从队列中查找作业?
是否有任何总体建议或设计缺陷或建议?
public class WorkerThread implements Runnable {
private BlockingQueue<Job> queue;
public WorkerThread() {
}
public void run() {
try {
queue.take().start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setQueue(BlockingQueue<Job> queue) {
this.queue = queue;
}
}
【问题讨论】:
-
我会使用
ExecutorService,它将队列与线程池结合起来,并将替换您的大部分代码。
标签: java multithreading runnable blockingqueue