美文网首页
java写一段死锁代码

java写一段死锁代码

作者: 小明17 | 来源:发表于2019-06-04 21:15 被阅读0次
public class Solution{
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (Solution.o1){
                    System.out.println("thread 1 get o1");
                    try {
                        Thread.sleep(100);
                        synchronized (Solution.o2){
                            System.out.println("thread1 get o2");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (Solution.o2){
                    System.out.println("thread 2 get o2");
                    try {
                        Thread.sleep(100);
                        synchronized (Solution.o1){
                            System.out.println("thread2 get o1");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }
}

相关文章

网友评论

      本文标题:java写一段死锁代码

      本文链接:https://www.haomeiwen.com/subject/ygtdxctx.html