死锁是如何造成的?

2020/08/13 99

synchronized

不同的线程分别占用对方所需要的🔒不放弃,双方都在等待对方率先释放🔒,以便自己执行后面的操作,相互僵持,形成了死锁。
出现死锁后,不会出现异常,不会有任何提示,线程一直处于阻塞状态,无法继续。

Java

public static void main(String[] args) {
    var s1 = new StringBuffer();
    var s2 = new StringBuffer();
    new Thread() {
        @Override
        public void run() {
            synchronized (s1) {
                s1.append("a");
                s2.append("1");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (s2) {
                    s1.append("b");
                    s2.append("2");
                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }
    }.start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (s2) {
                s1.append("c");
                s2.append("3");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (s1) {
                    s1.append("d");
                    s2.append("4");
                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }
    }).start();
}

C#

static void Main(string[] args)
{
    var s1 = new StringBuilder();
    var s2 = new StringBuilder();
    new Thread(() =>
    {
        lock (s1)
        {
            s1.Append("a");
            s2.Append("1");
            Thread.Sleep(1000);
            lock (s2)
            {
                s1.Append("b");
                s2.Append("2");
                Console.WriteLine(s1);
                Console.WriteLine(s2);
            }
        }
    }).Start();
    new Thread(() =>
    {
        lock (s2)
        {
            s1.Append("c");
            s2.Append("3");
            Thread.Sleep(1000);
            lock (s1)
            {
                s1.Append("d");
                s2.Append("4");
                Console.WriteLine(s1);
                Console.WriteLine(s2);
            }
        }
    }).Start();
}