Java中C#lock的等价物?

Java中C#lock的等价物?,c#,java,multithreading,C#,Java,Multithreading,Java中C#lock的等价物 例如: public int Next() { lock (this) { return NextUnsynchronized(); } } 如何将此C#方法移植到Java public int Next() { synchronized (this) { return NextUnsynchronized(); } } 就这样。下一个代码更好 public synchronized int Next() {

Java中C#lock的等价物

例如:

public int Next() {
  lock (this) {
    return NextUnsynchronized();
  }
}
如何将此C#方法移植到Java

public int Next() {
    synchronized (this) {
        return NextUnsynchronized();
    }
}
就这样。下一个代码更好

public synchronized int Next() {
    return NextUnsynchronized();
}

同步方法似乎是一个很好的解决方案@用户311311311请选择答案>o@Lee您必须发布与答案/问题相关的评论。不要以这种方式使用评论;在您的示例中显然不需要,但在一般情况下,您应该编写try{…}finally{lock.unlock();}
java.util.concurrent.locks.Lock    
lock.lock();

    int newCount = ++count;
    lock.unlock();