- The preceding program has two tasks that count primes. Now we want to do some work with them. Change
countPrimes
to public Runnable producePrimes(BigInteger start, long length, BlockingQueue<BigInteger> queue)
Instead of incrementing and returning counters, put any primes into the queue. Use put
, not add
.
- Add a method
public Runnable consumePrimes(BlockingQueue<BigInteger> queue)
that removes primes from the queue and prints those that have at most three distinct digits. Here is a method for getting all distinct characters in a string:
private static String distinct(String s)
{
StringBuilder result = new StringBuilder();
int i = 0;
while (i < s.length())
{
int cp = s.codePointAt(i);
int cc = Character.charCount(cp);
if (result.indexOf(s.substring(i, i + cc)) == -1)
result.appendCodePoint(cp);
i += cc;
}
return result.toString();
}
- How does the consumer know when it is done? Come up with some mechanism that works.
- In the
main
method, make an ArrayBlockingQueue
of capacity 1000. Change the newFixedThreadPool
call to have 3 threads. Add the three runnables
producePrimes(new BigInteger("1000000000000000"), 500_000, queue);
producePrimes(new BigInteger("1000000000500000"), 500_000, queue);
consumePrimes(queue, ...);
- Run the program. What primes do you get?