FileDocCategorySizeDatePackage
PoolLoopHandler.javaAPI DocExample2369Sat May 29 23:12:54 BST 2004javathreads.examples.ch15

PoolLoopHandler

public class PoolLoopHandler extends Object implements Runnable

Fields Summary
protected static ThreadPoolExecutor
threadpool
protected static int
maxThreads
protected int
startLoop
protected int
endLoop
protected int
curLoop
protected int
numThreads
Constructors Summary
public PoolLoopHandler(int start, int end, int threads)

        numThreads = threads;
	getThreadPool(numThreads);
        setRange(start, end);
    
Methods Summary
static synchronized voidgetThreadPool(int threads)


         
        if (threadpool == null)
	    threadpool = new ThreadPoolExecutor(
				1, 1,
				50000L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(),
				new PoolHandlerFactory());
	if (threads > maxThreads) {
	    maxThreads = threads;
	    threadpool.setMaximumPoolSize(maxThreads);
	    threadpool.setCorePoolSize(maxThreads);
	}
    
public voidloopDoRange(int start, int end)

    
protected synchronized javathreads.examples.ch15.PoolLoopHandler$LoopRangeloopGetRange()

        if (curLoop >= endLoop)
            return null;
        LoopRange ret = new LoopRange();
        ret.start = curLoop;
        curLoop += (endLoop-startLoop)/numThreads+1;
        ret.end = (curLoop<endLoop)?curLoop:endLoop;
        return ret;
    
public voidloopProcess()

        reset();
        FutureTask t[] = new FutureTask[numThreads];
        for (int i = 0; i < numThreads; i++) {
            t[i] = new FutureTask(this, null);
            threadpool.execute(t[i]);
        }
        for (int i = 0; i < numThreads; i++) {
	    try {
                t[i].get();
	    } catch (ExecutionException ee) {
	    } catch (InterruptedException ie) {
	    }
        }
    
public synchronized voidreset()

        curLoop = startLoop;
    
public voidrun()

        LoopRange str;
        while ((str = loopGetRange()) != null) {
            loopDoRange(str.start, str.end);
        }
    
public synchronized voidsetRange(int start, int end)

        startLoop = start;
        endLoop = end;
        reset();