不使用`synchronized`关键字的线程安全代码? [英] Thread-safe code without using the `synchronized` keyword?

查看:78
本文介绍了不使用`synchronized`关键字的线程安全代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用 synchronized 关键字的情况下,使代码线程安全的可能方法是什么?

What are the possible ways to make code thread-safe without using the synchronized keyword?

推荐答案

实际上,有很多方法:


  1. 如果你没有可变状态,根本不需要同步。

  2. 如果可变状态仅限于单个线程,则无需同步。这可以通过使用局部变量或 <$ c $来完成。 c> java.lang.ThreadLocal

  3. 您还可以使用内置同步器。 java.util .concurrent.locks.ReentrantLock 具有与使用 synchronized 块和方法时访问的锁相同的功能,它甚至是更强大。

  1. No need for synchronization at all if you don't have mutable state.
  2. 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.
  3. You can also use built-in synchronizers. java.util.concurrent.locks.ReentrantLock has the same functionality as the lock you access when using synchronized blocks and methods, and it is even more powerful.

这篇关于不使用`synchronized`关键字的线程安全代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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