求解 多线程死锁
992
2022.10.05
发布于 未知归属地

下面这段代码为啥没有任何输出

 public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s1) {
                    s1.append('a');
                    s2.append('1');

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    synchronized (s2) {
                        s1.append('b');
                        s2.append('2');
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();

        new Thread(){
            @Override
            public void run() {

                synchronized (s2) {
                    s1.append('a');
                    s2.append('1');
                    System.out.println(1);
                    synchronized (s1) {
                        s1.append('b');
                        s2.append('2');
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();

    }
评论 (3)