何时在java中使用多线程中的volatile vs同步? [英] When to use volatile vs synchronization in multithreading in java?

查看:175
本文介绍了何时在java中使用多线程中的volatile vs同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时在多线程中使用volatile关键字vs同步?

When to use volatile keyword vs synchronization in multithreading?

推荐答案

使用 volatile 保证对变量的每次读访问都会看到写入该变量的最新值。只要您需要为多个指令稳定值,请使用 synchronized 。 (注意,这并不一定意味着多个语句;单个语句:

Use volatile to guarantee that each read access to a variable will see the latest value written to that variable. Use synchronized whenever you need values to be stable for multiple instructions. (Note that this does not necessarily mean multiple statements; the single statement:

var++; // NOT thread safe!

即使 var 不线程安全c $ c>被声明为 volatile 。你需要这样做:

is not thread-safe even if var is declared volatile. You need to do this:

synchronized(LOCK_OBJECT){var++;}

参见这里提供了这个问题的精彩摘要。

See here for a nice summary of this issue.

这篇关于何时在java中使用多线程中的volatile vs同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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