How to do it...

Follow these steps to implement the example:

  1. Create a class named Calculator that implements the Runnable interface:
        public class Calculator implements Runnable {
  1. Implement the run() method. This method will execute the instructions of the thread we are creating, so this method will calculate the prime numbers within the first 20000 numbers:
        @Override         public void run() {           long current = 1L;           long max = 20000L;           long numPrimes = 0L;            System.out.printf("Thread '%s': START\n",                            Thread.currentThread().getName());           while (current <= max) {             if (isPrime(current)) {               numPrimes++;             }             current++;           }           System.out.printf("Thread '%s': END. Number of Primes: %d\n",                          Thread.currentThread().getName(), numPrimes);         }
  1. Then, implement ...

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.