java线程池,然后尝试捕获下一个线程
我正试图建立一个线程池,使工人和工作机会被创造出来,当他们忙的时候,它不应该给他们工作的工人。然而,到目前为止,当我尝试运行它时,我有这段代码,因为我有两个try-and-catch-in-worker。java run()它只是不按顺序输出它们。我想让第一次尝试发生,这样可以显示所有工人都开始工作了,然后我想让它显示哪个工人开始工作了
如果有办法使用busy=true;说这个工人很忙,所以把工作交给下一个工人
工人。爪哇
public class Worker implements Runnable {
private final int id; // Unique worker ID.
private final JobStack jobStack; // Reference to the job stack.
private final ResourceStack resourceStack; // Reference to the resource stack.
private Job job; // Job being processed.
private Resource[] resources; // Resources being used for job being processed.
private boolean busy; // Indicates the status of the worker. True when they are working (executing jobs) and false when there are no more jobs left to execute.
private final Map<Integer, ArrayList<Integer>> jobsCompleted; // The job record of the worker. Stores each job's ID and the IDs of the resources used for each job.
// Constructor.
public Worker(int theId, JobStack theJobStack, ResourceStack theResourceStack) {
id = theId;
jobStack = theJobStack;
resourceStack = theResourceStack;
job = null;
busy = true;
jobsCompleted = new TreeMap<>();
}
public void run() {
try
{
System.out.println("Worker " + id + " started Work ");
Thread.sleep(100);
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
for (Job job = jobStack.pop(); job != null; job = jobStack.pop()) {
try{
System.out.println("Worker " + id + " started Job " + job.getId());
}
catch (Exception e)
{
System.out.println ("Exception is caught");
}
}
}
}
劳动力。爪哇
import java.util.logging.Level;
import java.util.logging.Logger;
public class Workforce {
private final Worker[] pool; // The worker population.
private int workerCount = 0; // Used to generate each worker's ID and to keep a record of the number of workers in the workforce.
Thread[] workerThreads;
private final JobStack jobStack; // Reference to the job stack.
private final ResourceStack resourceStack; // Reference to the resource stack.
// Constructor.
public Workforce(int size, JobStack theJobStack, ResourceStack theResourceStack) {
jobStack = theJobStack;
resourceStack = theResourceStack;
pool = new Worker[size];
for(int i=0; i<pool.length; i++) {
pool[i] = new Worker(workerCount, jobStack, resourceStack);
workerCount++;
}
workerThreads = new Thread[pool.length];
for(int i=0; i<workerThreads.length; i++) {
workerThreads[i] = new Thread(pool[i]);
}
}
/// UNDER CONSTRUCTION /////////////////////////////////////////////////////
// Starts all the worker threads.
public void start() {
for(int i=0; i<pool.length; i++) {
workerThreads[i] = new Thread(pool[i]);
workerThreads[i].start();}
}
// Checks whether all workers have finished.
public boolean allWorkersFinished() {
return false;
}
// Prints the job record of all workers.
public void printJobRecords() {
;
}
}
共 (0) 个答案