有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javaee应用中的多线程死锁

我是JavaEE的新手。我想知道在JavaEE应用层中是否存在一些常见的死锁情况,这是由于使用了Java同步原语-synchronized关键字造成的。如果是,请给出一个例子


共 (2) 个答案

  1. # 1 楼答案

    来自EJB3.1规范,第21.2.2章。编程限制:

    An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances, except if it is a Singleton session bean with bean-managed concurrency.

    推理也很有趣:

    Synchronization would not work if the EJB container distributed enterprise bean’s instances across multiple JVMs.

  2. # 2 楼答案

    public void myMethod1() throws Exception {
        synchronized (MyClass.class) {
    
            Thread.sleep(10*1000);
    
            synchronized (MyClass2.class) {
            }
        }
    }
    
    public void myMethod2() throws Exception {    
        synchronized (MyClass2.class) {
    
            Thread.sleep(10*1000);
    
            synchronized (MyClass1.class) {
            }
    
        }
    }
    

    从一个线程调用myMethod1,从另一个线程调用myMethod2,将出现死锁