How to do it...

Follow these steps to implement the example:

  1. Create a class called PrimeGenerator that extends the Thread class:
        public class PrimeGenerator extends Thread{
  1. Override the run() method including a loop that will run indefinitely. In this loop, process consecutive numbers beginning from one. For each number, calculate whether it's a prime number; if yes, as in this case, write it to the console:
        @Override         public void run() {           long number=1L;           while (true) {             if (isPrime(number)) {               System.out.printf("Number %d is Prime\n",number);             }
  1. After processing a number, check whether the thread has been interrupted by calling the isInterrupted() method. If this method returns true, the thread has been interrupted. In this case, ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.