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

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