简单的例子说一下死锁的问题

代码如下:

    /*
    这里记录一下死锁的概念,意思就是两个线程
    ,线程一占用了a锁,去拿b锁,线程二占用了b锁,想拿a锁,两个线程谁也没办法继续
     */
    static String a = "a";
    static String b = "b";

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized(a){
                    System.out.println("我先拿到a了,等两秒后去拿b");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("我现在去拿b");
                    synchronized (b){
                        System.out.println("a和b都拿到了-----这是不可能的");
                    }
                }
            }
        }).start();
        new Thread(()->{
            synchronized (b){
                System.out.println("我拿到b了,等一秒去拿a");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("我现在去拿a");
                synchronized (a){
                    System.out.println("b和a都拿到了-----也是不可能的");
                }
            }
        }).start();
    }

  

猜你喜欢

转载自www.cnblogs.com/super-hu/p/11934260.html