Waiting for Thread Completion + Thread Synchronization+Communicating Between Threads

PHOTO EMBED

Thu Dec 29 2022 19:28:09 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka

.join()
.start()
//When you access the same data from two different threads, you may cause a race condition. A race condition occurs when some inconsistency is caused by two threads trying to access the same shared data at the same time.We can prevent race conditions on shared data using the synchronized keyword in Java. In a threaded program, when you add synchronized to the definition of a function, it will ensure that for a given instance of a class, only one thread can run that method at a time.


/*Java offers ways to control thread execution from within threads as well, using the wait() and notifyAll() methods on Objects. These are primarily used to protect shared resources from being used by two threads at the same time, or to wait until some condition has changed in a thread.

When using wait() and notifyAll(), it is important to do so in a synchronized(this) block. When you create a synchronized(this) block, you are telling Java that you want to be the only thread accessing the fields of the class at a given moment. In the synchronized(this) block, you must:

Check the condition on which to wait.
Decide whether to wait (block the execution of the current thread) or notifyAll() (allow other threads to check their condition again and proceed)*/
import java.lang.Thread;
 
public class OrderDinnerProcess {
 private boolean foodArrived = false;
 
 private void printTask(String task) { System.out.println(Thread.currentThread().getName() + " - " + task);};
 
 public void eatFood() {
   printTask("Wow, I am starving!");
   try {
     synchronized (this) {
       while (!this.foodArrived) {
         printTask("Waiting for the food to arrive...");
         wait();
       }
     }
   } catch (InterruptedException e) {
     System.out.println(e);
   }
   printTask("Finally! Yum yum yum!!!");
 }
 
 public void deliverFood() {
   printTask("Driving food over...");
   try {
     Thread.sleep(5000);
     synchronized (this) {
       this.foodArrived = true;
       printTask("Arrived!");
       notifyAll();
     }
   } catch (InterruptedException e) {
     System.out.println(e);
   }
 }
 
 public static void main(String[] args) {
   OrderDinnerProcess p = new OrderDinnerProcess();
   try {
     for (int i = 0; i < 5; i++) {
       Thread eatFood = new Thread(() -> p.eatFood());
       eatFood.start();
     }
     Thread.sleep(1000);
     Thread delivery = new Thread(() -> p.deliverFood());
     delivery.start();
   } catch (InterruptedException e) {
     System.out.println(e);
   }
 }
}

content_copyCOPY