gpt4 book ai didi

java - 如何选择在 Java 中锁定什么对象?

转载 作者:搜寻专家 更新时间:2023-11-01 02:11:23 26 4
gpt4 key购买 nike

我已经阅读了关于如何正确使用 synchronized 的类似问题的答案。但是,他们似乎没有解释为什么会出现此问题。即使我将 synchronized 添加到我的 getValue 和 setValue 方法,我仍然会得到如下所示的输出。为什么会这样?

输出:

making set

Doing get

making set

Doing making set

get

Doing get

making set

making Doing get

set

代码:

package src;

public class StackNode {
private Object value;
private StackNode next;

private final Object lock = new Object();

public StackNode() {
setValue(null);
setNext(null);
}

public StackNode(Object o) {
value = 0;
next = null;
}

public StackNode(StackNode node) {
value = node.getValue();
next = node.getNext();
}

public synchronized Object getValue() {
System.out.print(" Doing ");
System.out.println(" get ");
System.out.flush();
return value;

}

public synchronized void setValue(Object value) {
System.out.print(" making ");
System.out.println(" set ");
System.out.flush();
this.value = value;
}

public synchronized StackNode getNext() {
return next;
}

public synchronized void setNext(StackNode next) {
this.next = next;
}
}

测试:

public class TestStackNode {
private final static StackNode node = new StackNode();

@Test
public void getSetValueTest() throws InterruptedException{
node.setValue("bad");
Runnable setValue = new Runnable(){
@Override
public void run() {
node.setNext(new StackNode());
node.setValue("new");
}
};

Runnable getValue = new Runnable(){
@Override
public void run() {
Assert.assertEquals("new", node.getValue());
}
};
List<Thread> set = new ArrayList<Thread> ();
List<Thread> get = new ArrayList<Thread> ();
for (int i = 0; i < 30000; i++){
set.add( new Thread(setValue));
get.add(new Thread(getValue));
}

for (int i = 0; i < 30000; i++){
set.get(i).start();
get.get(i).start();
}

for (int i = 0; i < 30000; i++){
set.get(i).join();
get.get(i).join();
}
}

最佳答案

这应该可以解决问题。

public Object getValue() {
synchronized(System.out){
System.out.print(" Doing ");
System.out.println(" get ");
System.out.flush();
return value;
}

}

关于java - 如何选择在 Java 中锁定什么对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425645/

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