【问题标题】:Threads using same method in parallel并行使用相同方法的线程
【发布时间】:2013-02-11 15:03:13
【问题描述】:

是否有可能出现这种行为:

一个线程(T1)调用某个方法,例如compute(10);

当该函数仍在执行时,另一个线程再次调用它(使用其他参数),例如compute(20);

如果方法

public int compute(int i) {
    return i+20;
}

每个线程都会得到正确的结果吗?

我希望 T1 得到 20,而 T2 得到 40

【问题讨论】:

  • 嗯,T1 会得到 30,是的。我建议你写一些代码并尝试一下。

标签: java multithreading


【解决方案1】:

由于您只使用局部变量(方法参数是局部的),是的,它是安全的。

public class Computer {
    public int compute(int i) {
        return i+20;
    }
}

如果您将使用实例变量静态变量,那么您应该在变量中的每个readwrite 都有synchronized

public class Computer {
    private int increment;

    public synchronized int compute(int i) {
        return i+increment;  // <-- reads increment
    }

    private synchronized void setIncrement(int increment) {
         this.increment = increment;  // <-- writes increment
    }
}

【讨论】:

  • 接受这个答案是正确的,因为它更完整。
【解决方案2】:

简短的回答,是的。每个线程都有自己的方法中使用的数据堆栈,该堆栈与其他线程完全分开。只有当数据(例如类级别变量)在线程之间共享时,您才需要担心冲突。

【讨论】:

    【解决方案3】:

    假设您的compute 方法实现是:

    int compute(int i) {
      return i + 20;
    }
    

    那么每个线程都会得到正确的结果,因为这个方法不使用共享状态。

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 2011-11-24
      • 2017-10-23
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 2013-08-30
      相关资源
      最近更新 更多