【问题标题】:asynchronous function with a thread带线程的异步函数
【发布时间】:2013-01-11 20:16:48
【问题描述】:

我偶然发现了一个我不清楚的问题。

A.使用 Java 1.4,将以下函数包装在一个线程中,以便可以异步调用它,并提供一种稍后检索返回值的方法:

B.在 Java 5 中如何做同样的事情

int someMethod(int i) { return i++; }

我认为是解决方案之一:编写一个具有两个公共方法 void synchronized calculate(int i)int getValue() 的类。 calculate 启动线程并设置私有变量。

在 java 1.5 中,我可以使用 AtomincInteger。这是答案吗?

【问题讨论】:

    标签: java multithreading jvm java-5


    【解决方案1】:

    在 Java 1.5 中,我很确定您会使用 Future 来返回结果。我不确定 1.4 的等效版本,但看起来 this question 涵盖了相同的领域。

    【讨论】:

      【解决方案2】:

      Mybe 你可以在1.5 or later 中使用双重检查锁定:

      private volatile int privateValue = 0;
      
      public void calculate(int i) {
          int result = getValue(i);
          if (privateValue != result) {
              synchronized (this) {
                  if (privateValue != result) {
                      privateValue = result;
                  }
              }
          }
      
      }
      
      public int getValue(){
          return privateValue;
      }
      

      确保您的 privateValue 必须声明为 volatile

      关于double check locking的更多信息。

      The "Double-Checked Locking is Broken" Declaration.

      【讨论】:

        【解决方案3】:

        calculate()方法把结果放到BlockingQueue queue中,getValue()方法调用queue.take(),这样就等待结果还没有计算出来。

        如果可以多次调用 getValue() 方法,请注意额外的编程工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-28
          • 1970-01-01
          • 1970-01-01
          • 2020-01-15
          • 2021-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多