Site Search:

PrimeProducer.java

Back>

We can easily fix the previous example BrokenPrimeProducer.java with interrupt() method.
Pay attention to Thread.currentThread() vs. this -- inside run(), this and Thread.currentThread() refers to the same thread object, which is the one created by pp.start();. In cancel(), this refers to the thread created by pp.start();, Thread.currentThread() refers to the calling thread, which is the main thread.


CHAP7>cat PrimeProducer.java 
import java.math.BigInteger;
import java.util.concurrent.*;

/**
 * PrimeProducer
 * <p/>
 * Using interruption for cancellation
 */
class PrimeProducer extends Thread {
    private final BlockingQueue<BigInteger> queue;

    PrimeProducer(BlockingQueue<BigInteger> queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            BigInteger p = BigInteger.ONE;
            System.out.println(Thread.currentThread() + " started.");
            System.out.println(this + " started.");
            while (!Thread.currentThread().isInterrupted())
                queue.put(p = p.nextProbablePrime());
        } catch (InterruptedException consumed) {
        }
    }

    public void cancel() {
        System.out.println(Thread.currentThread().toString() + " is calling interrupt().");
        System.out.println(this + " will be interrupted.");
        interrupt();
    }
    
    public static void main(String args[]) {
        PrimeProducer pp = new PrimeProducer(new LinkedBlockingQueue<BigInteger>(5));
        System.out.println(pp.queue.size());
        pp.start();
        try {
            Thread.sleep(1000);
            pp.cancel();
            System.out.println(pp.queue.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
CHAP7>javac PrimeProducer.java 
CHAP7>java PrimeProducer
0
Thread[Thread-0,5,main] started.
Thread[Thread-0,5,main] started.
Thread[main,5,main] is calling interrupt().
Thread[Thread-0,5,main] will be interrupted.
5
CHAP7>