Friday, February 13, 2009

Thread DeadLock

If two threads are waiting for each other forever,that situation is considered as deadlock.(a lock without key is the deadlock)
We can present the dead lock occurrence but we const resolve.
Dead lock Example:
Class A
{
Public synchrozied void foo(B b)
{
System.out.println(“thread t1 entered into foo”);
try
{
Thread.sleep(2000);
}
catch(IE e){}
System.out.println(“thread t1 calling B’s last method”)
b.last();
}
Public synchronized void last()
{
System.out.println(“a class last method”);
}
}
Class B
{
Public synchronized void bar(A a)
{
System.out.println(“thread t2 entered into bar”);
try
{
Thread.sleep(2000);
{
Catch(intereped Exceptiom e){}
System.out.println(“thread t2 calling Ab last method);
a.last();
}
Public synchronized void last()
{
System.out.println(“B class last method”);
}
}
class DeadlockExample
{
A a=new A();
B b=new B();
DeadLock(){
Thread.currentThread().setName("main thread");
Thread t=new Thread(this);
t.start();
b.bar();
}
Public static void main(string[]args)
{
Deadlock d=new Deadlock();
}
Public void run()
{
a.foo(b);
}
}

0 comments:

Post a Comment