FirstThread.java
public class FirstThread {
public synchronized void startProcess(SecondThread sec) throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name + " Entered FirstThread.startProcess");
Thread.sleep(1000);
System.out.println("Trying to call SecondThread.last");
sec.last();
}
public synchronized void last() throws Exception {
System.out.println("Inside FirstThread.last");
}
}
SecondThread.java
public class SecondThread {
public synchronized void startJob(FirstThread fi) throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name + " Entered SecondThread.startJob");
Thread.sleep(1000);
System.out.println("Trying to call FirstThread.last");
fi.last();
}
public synchronized void last() throws Exception {
System.out.println("Inside SecondThread.last");
}
}
TestDeadLock.java
public class TestDeadLock implements Runnable
{
FirstThread a = new FirstThread();
SecondThread b = new SecondThread();
TestDeadLock()throws Exception
{
Thread.currentThread().setName("my Main Thread");
Thread t = new Thread(this,"Racing Thread");
t.start();
a.startProcess(b);
System.out.println("A has acquired lock on B");
System.out.println("Main thread continues...");
}
public void run()
{
try
{
b.startJob(a);
System.out.println("Racing Thread continues here..");
}
catch(Exception e)
{
System.out.println("Exception in Racing Thread "+e);
}
}
public static void main(String args[])throws Exception
{
new TestDeadLock();
}
}
Recent Comments