本文介绍了同步方法以递归方式调用自身。这打破了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的关键在于说明Java没有像我预期的那样工作。

The point of this question is to illustrate that Java is not working as I expected.

您希望以下代码表现如何?

How would you expect the following code to behave?

public class SynchTester {
  private static SynchTester synchTester;

  public synchronized static SynchTester getSynchTester(){
    if(synchTester==null){
      synchTester = new SynchTester();
    }

    return synchTester;
  }

  private SynchTester() {
    SynchTester myTester = getSynchTester();
  }

  public static void main(String[] args) {
    SynchTester tester = SynchTester.getSynchTester();
  }
}

我希望它会挂起,等待死锁递归完成,但它抛出StackOverflow。明显同步不会阻止访问同一个线程。

I would expect it to hang with a deadlock waiting on the recursion to complete, but instead it throws StackOverflow. Evidently synchronized does not block access to the same thread.

这是一个错误吗?

推荐答案

在Java中,同步锁是。

In Java, synchronized locks are reentrant.

来源:见

这篇关于同步方法以递归方式调用自身。这打破了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 03:12