Deadlock in Java Multithreading

aimtocode.COM

Dead lock

Deadlock is an error that can be encountered in multithread programs. It occurs when two or more threads wait indefinitely for each other to relinquish locks.

Deadlock situations can arise that involve more than two threads. Assume that Thread1 waits for a lock held by Thread2 waits for a lock held by Thread3. Thread3 waits for a lock held by Thread1.

aimtocode.COM
aimtocode.COM

Example 1:

Deadlock Example



Output :

Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...

Deadlock Solution Example

Example :



Output :

Thread 1: Holding lock 1...
Thread 1: Waiting for lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 1...
Thread 2: Waiting for lock 2...
Thread 2: Holding lock 1 & 2...
aimtocode.COM