I have to do schoolwork, and I have some code done, but got some questions:
must create a boss-workers application in java.
- I have these classes:
Main WorkerThread BossThread Job
Basically what I want to do is, that BossThread
holds a BlockingQueue
and workers go there and look for Jobs
.
Question 1:
At the moment I start 5 WorkingThreads
and 1 BossThread
.
Main:
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();
BossThread:
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;
}
Is this normal, or I should create WorkerThreads
in my BossThread
?
Question 2:
As you see I am giving the queue to each WorkerThread
, is that reasonable or I could store the queue only in one place?
Question 3:
Must I keep my BossThread
running somehow, just to wait if user adds more stuff to queue? And how I keep WorkerThreads
running, to look for jobs from queue?
Any overall suggestions or design flaws or suggestions?
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;
}
}