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

Question 6

The document contains code for two threads that attempt to synchronize access to two lock objects. Thread 1 acquires lock 1, then waits for lock 2, while thread 2 acquires lock 2 first and waits for lock 1, demonstrating potential deadlock between the threads.

Uploaded by

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

Question 6

The document contains code for two threads that attempt to synchronize access to two lock objects. Thread 1 acquires lock 1, then waits for lock 2, while thread 2 acquires lock 2 first and waits for lock 1, demonstrating potential deadlock between the threads.

Uploaded by

bb m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Question 5:

public class Main {


public static Object Lock1 = new Object();
public static Object Lock2 = new Object();

public static void main(String args[]) {


ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}

private static class ThreadDemo1 extends Thread {


public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}

private static class ThreadDemo2 extends Thread {


public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Testing the cod:

You might also like