// Class ThreadPool implements a thread pool. import java.util.*; import gov.nasa.jpf.jvm.Verify; public class ThreadPool { private LinkedList jobQueue = new LinkedList(); private Object cond = new Object(); Thread[] t; int numThreads; private int activeThreads = numThreads; private boolean done = false; // Constructor pre-spawn threads for the pool public ThreadPool(int numThreads) { this.numThreads = numThreads; t = new Thread[numThreads]; for(int i = 0; i < numThreads; i++) { t[i] = new PoolThread(); t[i].start(); } } // Method empty checks to see if the job queue is empty public synchronized boolean QueueEmpty(){ return(jobQueue.isEmpty()); } // Method addJob is obtained by applying the translation given in [8] // directly to coarse-grained solution public synchronized void addJob(GenericJob job) { jobQueue.add(job); notify(); } private synchronized GenericJob getJob() { while(jobQueue.isEmpty()) { activeThreads--; if(activeThreads==0) {done=true; notifyAll();} else{ try {wait();} catch (InterruptedException e){} } if(done) return null; activeThreads++; } return (GenericJob) jobQueue.removeFirst(); } // Implementation of a job thread (refer to c1 in Section 2.4) private class PoolThread extends Thread { public void run() { GenericJob job; while(true) { job = getJob(); if (job==null) break; while(job.execute()); } } } }