Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to show the digital clock on the console.

Java Code Example — Multithreading Programs

ADVERTISEMENT

Write a program to show the digital clock on the console.

Objective

Write a Java program to simulate a digital clock on the console using Thread.sleep().

Algorithm / Approach

  1. Start an infinite while(true) loop.
  2. Inside the loop, get the current time using new Date() and extract hours, minutes, and seconds.
  3. Print the time using System.out.printf with the carriage return character \r to overwrite the same line.
  4. Pause the current thread for exactly 1 second using Thread.sleep(1000) inside a try-catch block.
Clock.java
import java.util.*;
class Clock {
 public static void main(String[] a)
 {
  Date d = null;
  while(true) {
   d = new Date();
   int x = d.getHours();
   int y = d.getMinutes();
   int z = d.getSeconds();
   System.out.printf("%02d:%02d:%02d\r",x,y,z);
   try {
    Thread.sleep(1000);
   }catch(Exception e) { }
  }
 }
}

Explanation of the Program

  • The Thread.sleep(milliseconds) method temporarily suspends the execution of the current thread for a specified duration.
  • By sleeping for 1000 milliseconds (1 second) in an infinite loop, we can simulate the ticking of a clock.
  • The carriage return \r is a console trick: it moves the cursor back to the beginning of the current line without moving down to the next line, causing the new time to seamlessly overwrite the old time.

Complexity

Time Complexity O(1) - Infinite loop execution.
Space Complexity O(1)
ADVERTISEMENT