Sunday, 6 November 2016

Java - dead lock on String

class DeadLockString{

private static final String text1="this is text1";

private static final String text2="this is text2";

public static void main(String arr[]){

DeadLockString obj=new DeadLockString();

ThreadModelOne one=new ThreadModelOne();


ThreadModelTwo two=new ThreadModelTwo();

one.start();

two.start();
}

static class ThreadModelOne extends Thread{

public void run(){
synchronized(text1){
System.out.println("Lock aquired by thread model one in text1 ");
try{
Thread.sleep(2000);
}catch(Exception e){
System.out.println(e);
}

System.out.println("Waiting for lock on text2");

synchronized(text2){
System.out.println(" Locked aquired in text 1 and text 2 by thread model one.");
}
}
}
}


static class ThreadModelTwo extends Thread{

public void run(){
synchronized(text2){
System.out.println("Lock aquired by thread model one in text2 ");
try{
Thread.sleep(2000);
}catch(Exception e){
System.out.println(e);
}

System.out.println("Waiting for lock on text1");

synchronized(text1){
System.out.println(" Locked aquired in text 1 and text 2 by thread model two.");
}
}
}

}
}

No comments:

Post a Comment