Creating a deadlock can be pretty easy, consider two strings(str1, str2) accessed by two different threads say T1, T2.
- Thread T1 & T2 are mutually exclusive.
- T1 acquires thread on String str1 & goes to sleep.
- Thread T2 acquires the thread on str2 & goes to sleep.
- After the sleep interval of T1 gets over T1 tries to acquire the lock on str2, but sees that str2 is locked by T2. So it goes into blocking state
- Thread T2 also tries to acquire the lock on str1, but sees that str1 is locked by T1 & therefore goes into blocking state.
- The above point#4 & point #5 goes forever & none of the threads can proceed.
- Such a scenario is a deadlock.
class DeadlockExample
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 = "abc";
String s2 = "abcd";
Thread t1 = new Thread(new Thread1(s1,s2));
Thread t2 = new Thread(new Thread2(s1,s2));
t1.start();
t2.start();
}
}
class Thread1 implements Runnable{
private String str1;
private String str2;
public Thread1(String str1, String str2){
this.str1 = str1;
this.str2 = str2;
}
public void run(){
synchronized(str1){
try{Thread.sleep(1000);}catch(Exception e){}
synchronized(str2){
System.out.println("Thread1");
}
}
}
}
class Thread2 implements Runnable{
private String str1;
private String str2;
public Thread2(String str1, String str2){
this.str1 = str1;
this.str2 = str2;
}
public void run(){
synchronized(str2){
try{Thread.sleep(1000);}catch(Exception e){}
synchronized(str1){
System.out.println("Thread2");
}
}
}
}