Write a simple deadlock

Reference blog: https://www.cnblogs.com/mudao/p/5867107.html

public class Dead_Lock1 {
    public static String obj1 = "obj1";
    public static String obj2 = "obj2";

    public static void main(String[] args) {
        Thread thread1 = new Thread(new runnable1());
        Thread thread2 = new Thread(new runnable2());

        thread1.start();
        thread2.start();
    }
}

class runnable1 implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("runnable1 running.");

            while (true) {
                synchronized (Dead_Lock1.obj1) {
                    System.out.println("runnable1 lock obj1");
                    Thread.sleep(1000);
                    synchronized (Dead_Lock1.obj2) {
                        System.out.println("runnable1 lock obj2");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class runnable2 implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("runnable2 running.");
            while (true) {
                synchronized (Dead_Lock1.obj2) {
                    System.out.println("runnable2 lock obj2");
                    Thread.sleep(1000);
                    synchronized (Dead_Lock1.obj1) {
                        System.out.println("runnable2 lock obj2");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Obj 1 and obj 2 are string constants belonging to classes.

In the main function, two threads are running.

The object of runnable1 obtains the lock of obj 1 Thread.sleep(1000). Wait for the release of obj 2's lock to acquire obj 2's lock.

The object of runnable2 obtains the lock of oby2 Thread.sleep(1000). Wait for the release of the lock of obj 1 to obtain the lock of obj 1.

After two threads start executing, as shown in the above two lines. After two threads execute Thread.sleep(1000), they find that the locks they want to acquire are occupied by each other, and they cannot release the locks they already hold. So both sides wait for the release of each other's lock, causing deadlock.

 

Posted by madhu on Sat, 09 Nov 2019 08:35:03 -0800