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 thread is using when it's interrupted:
          for (int i = 0; i < 10; i++) { 
System.out.printf("%s ", new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.printf("The FileClock has been interrupted");
}
}
}
  1. We have implemented the thread. Now let's implement the main class of the example. Create a class called Main that contains the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create an object of the FileClock class and a thread to execute it. Then, start executing a thread:
        FileClock clock=new FileClock(); 
Thread thread=new Thread(clock);
thread.start();
  1. Call the sleep() method of the SECONDS attribute of the TimeUnit class in the main thread to wait for 5 seconds:
        try { 
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
};
  1. Interrupt the FileClock thread:
        thread.interrupt();
  1. Run the example and see the results.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.214