FileDocCategorySizeDatePackage
ThreadPool.javaAPI DocExample4294Thu Mar 11 22:56:22 GMT 2004javathreads.examples.appa

ThreadPool

public class ThreadPool extends Object

Fields Summary
Vector
objects
int
nObjects
CondVar
cvAvailable
CondVar
cvEmpty
BusyFlag
cvFlag
ThreadPoolThread[]
poolThreads
boolean
terminated
Constructors Summary
public ThreadPool(int n)


	   
		cvFlag = new BusyFlag();
		cvAvailable = new CondVar(cvFlag);
		cvEmpty = new CondVar(cvFlag);
		objects = new Vector();
		poolThreads = new ThreadPoolThread[n];
		for (int i = 0; i < n; i++) {
			poolThreads[i] = new ThreadPoolThread(this, i);
			poolThreads[i].start();
		}
	
Methods Summary
private voidadd(java.lang.Runnable target, java.lang.Object lock)

		try {
			cvFlag.getBusyFlag();
			if (terminated)
				throw new IllegalStateException("Thread pool has shutdown");
			objects.addElement(new ThreadPoolRequest(target, lock));
			nObjects++;
			cvAvailable.cvSignal();
		} finally {
			cvFlag.freeBusyFlag();
		}
	
public voidaddRequest(java.lang.Runnable target)

		add(target, null);
	
public voidaddRequestAndWait(java.lang.Runnable target)

		Object lock = new Object();
		synchronized(lock) {
			add(target, lock);
			lock.wait();
		}
	
public voidwaitForAll(boolean terminate)

		try {
			cvFlag.getBusyFlag();
			while (nObjects != 0)
				cvEmpty.cvWait();
			if (terminate) {
				for (int i = 0; i < poolThreads.length; i++)
					poolThreads[i].shouldRun = false;
				cvAvailable.cvBroadcast();
				terminated = true;
			}
		} finally {
			cvFlag.freeBusyFlag();
		}
	
public voidwaitForAll()

		waitForAll(false);