gpt4 book ai didi

具有 2 个不同对象的 Java 2 线程

转载 作者:行者123 更新时间:2023-11-30 07:49:28 26 4
gpt4 key购买 nike

给定下面提到的代码,假设我们有两个不同的线程 thread1、thread2 以及类 BCell 的两个不同对象 p1 和 p2。如果 thread1 执行 p1.swap(p2) 并且 thread2 同时执行 p2.swap(p1) 可能出现的问题是什么?我已经读过 herehere但它似乎没有帮助。

    class BCell {
int value;
public synchronized int getValue() {
return value;
}
public synchronized void setValue(int i) {
value=i;
}
public synchronized void swap(BCell x) {
int temp = getValue();
setValue(x.getValue);
x.setValue(temp);
}
}

最佳答案

Here is a synchronized instance method:

  public synchronized void add(int value){
this.count += value;
}

Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized.

A synchronized instance method in Java is synchronized on the instance (object) owning the method.

报价来源为here .

这意味着当您调用 p1.swap(p2) 时,它会阻止 p1 在该实例上的任何其他同步块(synchronized block)中使用,直到 p1.swap (p2) 完成。所以在你的情况下 setValue(x.getValue); 不能同时调用。

关于具有 2 个不同对象的 Java 2 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48543481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com