我一直在使用Java的synchronized块来使我的代码线程部分安全.我正在将通常可以使用synchronized块的数据结构移植到Java,但是我并不总是知道如何以典型的Java方式使用它们.
I have been making use of Java's synchronized blocks to make parts of my code thread safe. I am porting a data structure to java that can usually use synchronized blocks, but I don't always know how to use them in a typical Java way.
以下是一种情况的示例:
Here is an example of one scenario:
myMethod (Bool useLock) { if (useLock) { //locks the following section of code until unlocked. lockObject.lock(); } //do more stuff.... if (useLock) { //unlocks exclusive control of code. lockObject.unlock(); } }我该如何在Java中做到这一点?在这段代码中,有时我想锁定,有时却不想,但是我想对此保持聪明,而不必编写同一代码的两个版本.除了使用synchronized块以外,还有其他锁定Java的方法吗?
How do I do an equivalent of this in Java? In this code sometimes I want to lock and sometimes I don't, but I want to be smart about it and not have to write two versions of the same code. Are there other ways of locking in Java other than using synchronized blocks?
推荐答案您可以使用Lock对象, ReentrantLock 即可. docs.oracle/javase/tutorial/essential/concurrency /newlocks.html
You can use Lock objects, ReentrantLock in particular should do the work. docs.oracle/javase/tutorial/essential/concurrency/newlocks.html
或者您仍然可以使用synchronized块解决问题.您问题中的代码如下:
Or you can still solve the issue with synchronized blocks. The code from your question will look like:
myMethod (Bool useLock) { if (useLock) { synchronized (this) { criticalSection(); } } else { criticalSection(); } } criticalSection() { //do more stuff.... }或者,如果要保证类的不同实例之间的互斥,则应使用this以外的其他监视对象.例如TheClassName.class或该类的其他显式定义的静态变量.
Or if you want to guarantee the mutual exclusion among different instances of the class you should use other monitor object than this. For instance TheClassName.class or other explicitly defined static variable of that class.
更多推荐
如何有条件地锁定Java?
发布评论