How to pause a Thread?
A Thread can be paused by calling any of the below methods.
- Makes the current thread to sleep for the specified no. of milliseconds. After the sleep interval, the thread will be moved back to rerunnable.
- While sleeping, the thread does not release the lock on the object if it holds any lock.
- 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()
- Unlike Thread.sleep(), wait() is a call on a shared Object by a Thread.
- wait(long millis) and wait() are different ways to pause the thread execution.
- wait(long millis) method pauses the current thread for specified no. of milliseconds. After the wait interval, the thread will be available for running.
- 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.
- While waiting, Thread releases the lock which it holds.
- Wait() should be called from the synchronized context (Synchronized block or Synchronized code )only whereas Thread.sleep can be called from any context.
- 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
Post a Comment