0% found this document useful (0 votes)
6 views2 pages

Understanding Deadlock in Java Multithreading

Deadlock in Java occurs in multithreading when two threads are waiting for each other to release locks on resources, causing a standstill. The document provides an example with two threads attempting to lock two resources in opposite order, illustrating how deadlock can happen. The situation results in both threads being unable to proceed, as each is waiting for the other to release a lock.

Uploaded by

tanujayelamanchi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Understanding Deadlock in Java Multithreading

Deadlock in Java occurs in multithreading when two threads are waiting for each other to release locks on resources, causing a standstill. The document provides an example with two threads attempting to lock two resources in opposite order, illustrating how deadlock can happen. The situation results in both threads being unable to proceed, as each is waiting for the other to release a lock.

Uploaded by

tanujayelamanchi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Deadlock in Java

 Deadlock in Java is a part of multithreading.


 Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired
by another thread and second thread is waiting for an object lock that is acquired by first
thread.
 Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.

class TestDeadlockExample1
{
public static void main(String arg[]) {
final String resource1 = "Srinu";
final String resource2 = "Vinnu";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread()
{
public void run()
{
synchronized (resource1)
{
[Link]("Thread 1: locked resource 1");

try { [Link](100);} catch (Exception e) {}

synchronized (resource2)
{
[Link]("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread()
{
public void run()
{
synchronized (resource2)
{
[Link]("Thread 2: locked resource 2");
try { [Link](100);} catch (Exception e) {}

synchronized (resource1)
{
[Link]("Thread 2: locked resource 1");
}
}
}
};

[Link]();
[Link]();
}
}

You might also like