Thursday, June 15, 2023

Difference between Wait and Sleep, Yield in Java? Example

In Java, "wait," "sleep," and "yield" are three different concepts used for different purposes. 

1. Wait:

The wait() method is used in Java for thread synchronization. When a thread calls the wait() method on an object, it releases the lock it holds on that object and waits until another thread notifies it to resume. This is typically used in multi-threaded environments where threads need to coordinate their activities. 

Here's an example of using wait() and notify() to synchronize threads:


class Message {
   private String message;
   
   public synchronized void setMessage(String message) {
      this.message = message;
      notify(); // Notify waiting threads
   }
   
   public synchronized String getMessage() throws InterruptedException {
      while (message == null) {
         wait(); // Wait until message is available
      }
      String msg = message;
      message = null;
      return msg;
   }
}

2. Sleep: 

The sleep() method is used to pause the execution of the current thread for a specified period of time. It is typically used for introducing delays or to control the timing of certain operations in a program. 

Here's an example of using sleep() to introduce a delay:


public class SleepExample {
   public static void main(String[] args) {
      System.out.println("Before sleep");
      try {
         Thread.sleep(2000); // Sleep for 2 seconds
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      System.out.println("After sleep");
   }
}

In the above example, the program pauses for 2 seconds before printing "After sleep". 

3. Yield:

The yield() method is used to give a hint to the scheduler that the current thread is willing to give up its current execution time to allow other threads of the same priority to run. 

However, it's up to the scheduler to decide whether to honor this hint or not. 

Here's an example of using yield():


public class YieldExample {
   public static void main(String[] args) {
      Thread t1 = new Thread(() -> {
         for (int i = 0; i < 5; i++) {
            System.out.println("Thread 1: " + i);
            Thread.yield(); // Yield execution to other threads
         }
      });
      
      Thread t2 = new Thread(() -> {
         for (int i = 0; i < 5; i++) {
            System.out.println("Thread 2: " + i);
            Thread.yield(); // Yield execution to other threads
         }
      });
      
      t1.start();
      t2.start();
   }
}


In the above example, two threads, t1 and t2, are created and both invoke yield() after printing each number. This gives the scheduler an opportunity to switch between the threads during execution, although the actual behavior depends on the underlying system's scheduling algorithm. 

Overall, wait() and notify() are used for thread synchronization, sleep() is used for introducing delays, and yield() is used to suggest the scheduler to give other threads a chance to run.

No comments:

Post a Comment