RKTechGame | Thread Communication & Deadlocks in Java

Thread Communication (Inter-Thread Communication) kya hai?

Jab multiple threads ek doosre ke sath coordinate karte hain aur data share karte hain, tab thread communication kehte hain. Java me ye achieved hota hai wait(), notify(), aur notifyAll() methods ke through.

Ye sab methods object class ke hain aur synchronized context me hi use kiye jaate hain.

Inter-Thread Communication ka Example

class Chat {
  boolean flag = false;

  public synchronized void Question(String msg) {
    if (flag) {
      try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
    System.out.println(msg);
    flag = true;
    notify();
  }

  public synchronized void Answer(String msg) {
    if (!flag) {
      try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
    System.out.println(msg);
    flag = false;
    notify();
  }
}

class T1 implements Runnable {
  Chat m;
  String[] s1 = { "Hi", "How are you?", "I am fine" };
  public T1(Chat m1) {
    this.m = m1;
    new Thread(this, "Question").start();
  }
  public void run() {
    for (int i = 0; i < s1.length; i++) {
      m.Question(s1[i]);
    }
  }
}

class T2 implements Runnable {
  Chat m;
  String[] s2 = { "Hi", "I am good, thanks", "Great!" };
  public T2(Chat m2) {
    this.m = m2;
    new Thread(this, "Answer").start();
  }
  public void run() {
    for (int i = 0; i < s2.length; i++) {
      m.Answer(s2[i]);
    }
  }
}

public class ThreadCommDemo {
  public static void main(String[] args) {
    Chat m = new Chat();
    new T1(m);
    new T2(m);
  }
}

Output:

Hi
Hi
How are you?
I am good, thanks
I am fine
Great!

Deadlock kya hai?

Deadlock ek situation hai jab do ya usse zyada threads ek dusre ke resources ka intezaar karte rahte hain bina kabhi release kiye, jiski wajah se saare threads permanently block ho jate hain.

Deadlock ka Simple Example

class Resource {
  synchronized void foo(Resource r) {
    String name = Thread.currentThread().getName();
    System.out.println(name + " entered foo()");
    try { Thread.sleep(100); } catch (InterruptedException e) {}
    System.out.println(name + " trying to call bar()");
    r.bar(this);
  }
  synchronized void bar(Resource r) {
    String name = Thread.currentThread().getName();
    System.out.println(name + " entered bar()");
  }
}

public class DeadlockDemo {
  public static void main(String[] args) {
    final Resource r1 = new Resource();
    final Resource r2 = new Resource();

    Thread t1 = new Thread(() -> r1.foo(r2), "Thread-1");
    Thread t2 = new Thread(() -> r2.foo(r1), "Thread-2");

    t1.start();
    t2.start();
  }
}

Output dekhenge ki Thread-1 aur Thread-2 ek doosre ke lock ka wait kar rahe hain aur program hang ho jata hai (deadlock).