不使用`synchronized`关键字的线程安全代码? [英] Thread-safe code without using the `synchronized` keyword?
本文介绍了不使用`synchronized`关键字的线程安全代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在不使用 synchronized
关键字的情况下,使代码线程安全的可能方法是什么?
What are the possible ways to make code thread-safe without using the synchronized
keyword?
推荐答案
实际上,有很多方法:
- 如果你没有可变状态,根本不需要同步。
- 如果可变状态仅限于单个线程,则无需同步。这可以通过使用局部变量或 <$ c $来完成。 c> java.lang.ThreadLocal 。
- 您还可以使用内置同步器。
java.util .concurrent.locks.ReentrantLock
具有与使用synchronized
块和方法时访问的锁相同的功能,它甚至是更强大。
- No need for synchronization at all if you don't have mutable state.
- No need for synchronization if the mutable state is confined to a single thread. This can be done by using local variables or
java.lang.ThreadLocal
. - You can also use built-in synchronizers.
java.util.concurrent.locks.ReentrantLock
has the same functionality as the lock you access when usingsynchronized
blocks and methods, and it is even more powerful.
这篇关于不使用`synchronized`关键字的线程安全代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文