Multithreading in Java 6
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when first thread is waiting for an object lock, that is acquired by second thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Example of deadlock :
class Pen{}
class Paper{}
public class Write {
public static void main(String[] args)
{
final Pen pn =new Pen();
final Paper pr =new Paper();
// t1 tries to lock pn then pr
Thread t1 = new Thread(){
public void run()
{
synchronized(pn)
{
System.out.println("Thread1 is holding Pen");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pr)
{ System.out.println("Requesting for Paper"); }
}
}
};
// t1 tries to lock pr then pn
Thread t2 = new Thread(){
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is holding Paper");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
synchronized(pn)
{ System.out.println("requesting for Pen"); }
}
}
};
t1.start();
t2.start();
}
}
Output :
Thread1 is holding Pen
Thread2 is holding Paper
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )