2014-03-24 55 views
5

Java中C#锁定的等价物?Java中C#锁定的等价物?

例如:

public int Next() { 
    lock (this) { 
    return NextUnsynchronized(); 
    } 
} 

我如何端口这个C#方法的Java?

+0

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html – 0x90

回答

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

就是这样。接下来的代码更好。

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

这将是最好不要锁定'this'在大多数情况下...... –

+0

同步方法似乎是一个不错的解决方案! – user3111311

+0

@ user3111311请选择answer> o < – ikh

0
java.util.concurrent.locks.Lock  
lock.lock(); 

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

除非你需要尝试/最后,并使用'synchronized'在这里更接近...... –

+0

在你的例子中显然不需要,但在一般情况下,你应该写{try} finally {lock.unlock ();} –