我已经阅读了类似问题的答案,了解了如何正确使用 synchronized。然而,它们似乎没有解释为什么会出现这个问题。
即使我在 getValue 和 setValue 方法中添加了 synchronized,我仍然会得到以下输出。
为什么会发生这种情况呢? 输出:
即使我在 getValue 和 setValue 方法中添加了 synchronized,我仍然会得到以下输出。
为什么会发生这种情况呢? 输出:
代码: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();
}
}