在Java中如何选择要锁定的对象

在Java中如何选择要锁定的对象

我已经阅读了有关使用同步的正确方法的类似问题的答案。但是,他们似乎没有解释为什么会出现这个问题。
即使我在 getValue 和 setValue 方法中添加了 synchronized,我仍然得到如下输出。
为什么会发生这种情况?
输出:

代码:

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/

10-10 03:37