How to do it...

Follow these steps to implement the example:

  1. Create a class called ConsoleClock and specify that it implements the Runnable interface:
        public class ConsoleClock implements Runnable {
  1. Implement the run() method:
        @Override         public void run() {
  1. Write a loop with 10 iterations. In each iteration, create a Date object, write it to the console, and call the sleep() method of the SECONDS attribute of the TimeUnit class to suspend the execution of the thread for 1 second. With this value, the thread will be sleeping for approximately 1 second. As the sleep() method can throw an InterruptedException exception, we have to include some code to catch it. It's good practice to include code that frees or closes the resources the ...

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.