Monday, October 14, 2013

Deadlock in java sample

First Create Two Classes without implementation,

public class One{
}

public class Two{
}

then Create two Threads-----

public class ThreadOne implements Runnable{

One one;
Two two;
public ThreadOne(One one,Two two){
this.one=one;
this.two=two;
}
public void run() {
synchronized (one) {
try{
wait(87099);
}
catch (Exception e) {
// TODO: handle exception
}
System.out.println(two.toString());

}
}
}

Another Thread,

public class ThreadTwo implements Runnable{
One one;
Two two;
public ThreadTwo(One one,Two two){
this.one=one;
this.two=two;
}
public void run() {
synchronized (two) {
try{
wait(8799);
}
catch (Exception e) {
System.out.println("exception occered");
}
System.out.println(one.toString());

}
}
}

Just Create one class to test----
public class Test {

/**
* @param args
*/
public static void main(String[] args) {

One one = new One();
Two two = new Two();

ThreadOne threadOne = new ThreadOne(one, two);
ThreadTwo threadTwo = new ThreadTwo(one, two);
Thread t1 = new Thread(threadOne);
Thread t2 = new Thread(threadTwo);
t1.start();
t1.start();
}

}


output:


Exception in thread "main" core.java.babu.deadlockk.Two@1f33675
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at core.java.babu.deadlockk.Test.main(Test.java:18)



No comments:

Post a Comment