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

Implementation of Deadlock Through Java Program 2: Code

This Java program implements deadlock between two threads (t1 and t2) by having each thread try to lock two shared resources (resource1 and resource2) in different orders. The first thread t1 locks resource1, then waits to lock resource2. The second thread t2 locks resource1, then tries to lock resource2, causing a deadlock as both threads are waiting for a resource held by the other. The code prints output indicating which thread locks which resource to demonstrate the deadlock.

Uploaded by

Piyush Arora
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)
30 views2 pages

Implementation of Deadlock Through Java Program 2: Code

This Java program implements deadlock between two threads (t1 and t2) by having each thread try to lock two shared resources (resource1 and resource2) in different orders. The first thread t1 locks resource1, then waits to lock resource2. The second thread t2 locks resource1, then tries to lock resource2, causing a deadlock as both threads are waiting for a resource held by the other. The code prints output indicating which thread locks which resource to demonstrate the deadlock.

Uploaded by

Piyush Arora
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
You are on page 1/ 2

0802IT111033

Palak Arora
Implementation of Deadlock through Java Program 2


Code:

public class Deadlock_wait {
public static void main(String[] args) {

// These are the two resource objects we'll try to get locks for
final Object resource1 = "resource1";
final Object resource2 = "resource2";

// Here's the first thread. It tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {

// Lock resource 1
synchronized(resource1) {
System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(50); } catch (InterruptedException e) {}


synchronized(resource2) {
System.out.println("Thread 1: locked resource 2");
System.out.println("Thread 1: Put on wait, removed
lock on resource 1");
try{ resource1.wait(); } catch (InterruptedException e) {
}
}
}
};


Thread t2 = new Thread() {
public void run() {


synchronized(resource1) {
System.out.println("Thread 2: locked resource 1");
0802IT111033
Palak Arora

//try { Thread.sleep(50); } catch (InterruptedException e) {}

synchronized(resource2) {
System.out.println("Thread 2: locked resource 2");
}
}
}
};


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

Output 4:

You might also like