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. First, implement a program that has the problem exposed previously. Create a class called UnsafeTask and specify that it implements the Runnable interface. Declare a private java.util.Date attribute:
        public class UnsafeTask implements Runnable{           private Date startDate;
  1. Implement the run() method of the UnsafeTask object. This method will initialize the startDate attribute, write its value to the console, sleep for a random period of time, and again write the value of the startDate attribute:
        @Override         public void run() {           startDate=new Date();           System.out.printf("Starting Thread: %s : %s\n",                            Thread.currentThread().getId(),startDate);           try {  TimeUnit.SECONDS.sleep( (int)Math.rint(Math.random()*10)); ...

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