Deadlock in Java

 


Deadlock in Java

A deadlock in Java occurs when two or more threads are blocked forever, each waiting for the other to release a lock. Deadlocks can be challenging to detect and debug

Inter-thread Communication in Java

(Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class:

  • 1.   wait()
  • 2.   notify()
  • 3.   notifyAll()

Example 01:

package com.java.Multi_threading;

public class DeadlockExample {


static class Resource {

public synchronized void method1(Resource anotherResource) {

System.out.println(Thread.currentThread().getName() + " is executing method1()");

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

anotherResource.method2(this);

}


public synchronized void method2(Resource anotherResource) {

System.out.println(Thread.currentThread().getName() + " is executing method2()");

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

anotherResource.method1(this);

}

}


public static void main(String[] args) {

final Resource resource1 = new Resource();

final Resource resource2 = new Resource();


// Thread 1

new Thread(() -> {

resource1.method1(resource2);

}).start();


// Thread 2

new Thread(() -> {

resource2.method1(resource1);

}).start();

}

}


 

Post a Comment

0 Comments