Java Thread sleep and resume a thread

Introduction

Java Thread sleep and resume a thread

When calling the sleep() method, Thread leaves the CPU and stops its execution for a period of time.

During the sleeping, it's not consuming CPU time, so the CPU can be executing other tasks.

When Thread is sleeping and is interrupted, the method throws an InterruptedException.

It doesn't wait until the sleeping time finishes.


import java.util.concurrent.TimeUnit;
import java.util.Date;

public class Main {

  public static void main(String[] args) {
    // Creates a FileClock runnable object and a Thread
    // to run it/* w  ww .  j  a  v  a 2 s  .  c  o  m*/
    MyThread clock=new MyThread();
    Thread thread=new Thread(clock);
    
    // Starts the Thread
    thread.start();
    try {
      // Waits five seconds
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    };
    // Interrupts the Thread
    thread.interrupt();
  }
}
/**
 * Class that writes the actual date to a file every second
 * 
 */
class MyThread implements Runnable {
  @Override
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.printf("%s\n", new Date());
      try {
        // Sleep during one second
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        System.out.printf("The FileClock has been interrupted");
      }
    }
  }
}



PreviousNext

Related