如何有条件地锁定Java?

编程入门 行业动态 更新时间:2024-10-27 19:28:49
本文介绍了如何有条件地锁定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对象, 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?

本文发布于:2023-05-27 23:09:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/306064.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!