package com.JavaInterview.Programs;
/**
* Find Out Factorial of a number
*
* @author:http://javainterviewprograms.blogspot.in/
*
*/
/**
* Find Out Factorial of a number
*
* @author:http://javainterviewprograms.blogspot.in/
*
*/
public class ThreadDeadlock {
public static Object lock1 = new Object();
public static
Object lock2 = new Object();
public static void main(String args[]) {
Thread1 t1 =
new Thread1();
Thread2 t2 =
new Thread2();
t1.start();
t2.start();
}
private static class Thread1 extends Thread {
public void run() {
synchronized
(lock1) {
System.out.println("Thread
1 :holding the lock1 ...");
try {
Thread.sleep(10);
} catch
(InterruptedException e) {
}
System.out.println("Thread 1 :waiting for lock 2....");
synchronized
(lock2) {
System.out.println("Thread 1: holding lock1 and 2...");
}
}
}
}
private static class Thread2 extends Thread {
public void
run() {
synchronized
(lock2) {
System.out.println("Thread 2 :holding the lock2");
try {
Thread.sleep(20);
} catch
(InterruptedException e) {
}
System.out.println("Thread 2 : waiting for lock1 ...");
synchronized
(lock1) {
System.out.println("Thread 2 : holding both lock1 and 2..");
}
}
}
}
}
Output :
Thread 2 :holding the lock2
Thread 1 :holding the lock1 ...
Thread 1 :waiting for lock 2....
Thread 2 : waiting for lock1.
...
No comments:
Post a Comment