Site Search:

PrimeGenerator.java

Back>

In the following example, there is a while loop in the run() method. A volatile boolean variable cancelled is used as the cancellation flag. Calling cancel() method set the flag to true, which causes the while loop in run() method to exit. In aSecondOfPrimes method , main thread submits the runnable to ExecutorService, which immediately runs it in a worker thread. One second later, main thread calls cancel() to set the flag, so that the worker thread finishes the looping.

CHAP7>cat PrimeGenerator.java 
import static java.util.concurrent.TimeUnit.SECONDS;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;

/**
 * PrimeGenerator
 * <p/>
 * Using a volatile field to hold cancellation state
 */
public class PrimeGenerator implements Runnable {
    private static ExecutorService exec = Executors.newCachedThreadPool();

    private final List<BigInteger> primes
            = new ArrayList<BigInteger>();
    private volatile boolean cancelled;
    
    public static void main(String...args) {
        try {
            List<BigInteger> list = aSecondOfPrimes();
            System.out.println(list.size());
            exec.shutdown();
            exec.awaitTermination(10, SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled) {
            p = p.nextProbablePrime();
            synchronized (this) {
                primes.add(p);
            }
        }
    }

    public void cancel() {
        cancelled = true;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<BigInteger>(primes);
    }

    static List<BigInteger> aSecondOfPrimes() throws InterruptedException {
        PrimeGenerator generator = new PrimeGenerator();
        exec.execute(generator);
        try {
            SECONDS.sleep(1);
        } finally {
            generator.cancel();
        }
        return generator.get();
    }
}
CHAP7>javac PrimeGenerator.java 
CHAP7>java PrimeGenerator
12039

CHAP7>