zoukankan      html  css  js  c++  java
  • java死锁问题

    package selenium_demo;
    
    class A {
        synchronized void foo(B b) {
            String name = Thread.currentThread().getName();
            System.out.println(name + " entered A.foo");
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                System.out.println("A Interrupted");
            }
            System.out.println(name + " trying to call B.last()");
            b.last();
        }
    
        synchronized void last() {
            System.out.println("Inside A.last");
        }
    }
    
    class B {
        synchronized void bar(A a) {
            String name = Thread.currentThread().getName();
            System.out.println(name + " entered B.bar");
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                System.out.println("B Interrupted");
            }
            System.out.println(name + " trying to call A.last()");
            a.last();
        }
    
        synchronized void last() {
            System.out.println("Inside B.last");
        }
    }
    
    class Deadlock implements Runnable {
        A a = new A();
        B b = new B();
    
        Deadlock() {
            Thread.currentThread().setName("MainThread");
            Thread t = new Thread(this, "RacingThread");
            t.start();
            a.foo(b); // get lock on a in this thread.
            System.out.println("Back in main thread");
        }
    
        public void run() {
            b.bar(a); // get lock on b in other thread.
            System.out.println("Back in other thread");
        }
    
        public static void main(String args[]) {
            new Deadlock();
        }
    }

    最后输出:

    MainThread entered A.foo
    RacingThread entered B.bar
    MainThread trying to call B.last()
    RacingThread trying to call A.last()
    

      为什么会死锁?  a.foo(b)    b.bar(a)   ,互相调用对方last,都没用着,怎么会锁呢?

    锁的是对象,not单个什么玩意

  • 相关阅读:
    互联网产品经理入门知识
    ceph的架构和概念学习
    使用cephadm安装ceph octopus
    split命令,文件切割
    openssh升级到8.4版本
    Shell写一个显示目录结构
    nsenter 工具的使用
    『Spring Boot 2.4新特性』减少95%内存占用
    Dubbo 一篇文章就够了:从入门到实战
    for update 和 rowid 的区别
  • 原文地址:https://www.cnblogs.com/qbmiller/p/3666383.html
Copyright © 2011-2022 走看看