Understanding Deadlock in Thread

DeadLockDemo.java

package thread;

public class DeadLockDemo {

    public static void main(String args[]) {
        String s1 = "Dead";
        String s2 = "Lock";
        MyThread1 m = new MyThread1(s1, s2);
        MyThread2 m1 = new MyThread2(s1, s2);
    }
}

class MyThread1 extends Thread {

    String s1;
    String s2;

    MyThread1(String s1, String s2) {
        this.s1 = s1;
        this.s2 = s2;
        start();
    }

    @Override
    public void run() {
        while (true) {
            synchronized (s1) {
                synchronized (s2) {
                    System.out.println(s1 + s2);
                }
            }
        }
    }
}

class MyThread2 extends Thread {

    String s1;
    String s2;

    MyThread2(String s1, String s2) {

        this.s1 = s1;
        this.s2 = s2;
        start();
    }

    public void run() {
        while (true) {
            synchronized (s2) {
                synchronized (s1) {
                    System.out.println(s2 + s1);
                }
            }
        }
    }
}
Advertisements
This entry was posted in Core JAVA, Just 4 Knowledge. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s