如何有条件地锁定Java? [英] How do I conditionally lock in Java?

查看:104
本文介绍了如何有条件地锁定Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用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对象, http://docs.oracle.com/javase/tutorial/essential/concurrency /newlocks.html

You can use Lock objects, ReentrantLock in particular should do the work. http://docs.oracle.com/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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆