How to pause a Thread?

A Thread can be paused by calling any of the below methods.


Thread.sleep(long millis) 
  1. Makes the current thread to sleep for the specified no. of milliseconds. After the sleep interval, the thread will be moved back to rerunnable.
  2. While sleeping, the thread does not release the lock on the object if it holds any lock.
  3. While sleeping if any another other thread interrupts the current thread, the current thread throws an InterruptedException.
public class SleepExample {
   public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() +" is going to sleep for 1 sec");
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main Thread is woken now");
    }
}

Output
main is going to sleep for 1 sec
Main Thread is woken now


wait()  
  1. Unlike Thread.sleep(), wait() is a call on a shared Object by a Thread.
  2. wait(long millis) and wait() are different ways to pause the thread execution.
  3. wait(long millis) method pauses the current thread for specified no. of milliseconds. After the wait interval, the thread will be available for running.
  4. wait() method pauses the current thread to wait forever. To make the thread Rerunnable again, another thread has to call notify() on the same shared object. 
  5. While waiting, Thread releases the lock which it holds. 
  6. Wait() should be called from the synchronized context (Synchronized block or Synchronized code )only whereas Thread.sleep can be called from any context. 
  7. calling wait() method outside the Synchronized context results in  IllegalMonitorStateException.


Yield()
  It releases CPU hold so that other thread which is in the race for CPU time can grab it.


Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)