O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required