'同步'是什么意思? [英] What does 'synchronized' mean?

查看:166
本文介绍了'同步'是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 synchronized 关键字的用法和重要性有一些疑问。

I have some questions regarding the usage and significance of the synchronized keyword.


  • synchronized 关键字有什么意义?

  • 什么方法应该同步

  • 这是什么意思,这是编程和逻辑?

  • What is the significance of the synchronized keyword?
  • When should methods be synchronized?
  • What does it mean programmatically and logically?

推荐答案

synchronized 关键字是关于不同线程的读写相同的变量,对象和资源。这不是Java中的一个简单主题,但这里引用了Sun:

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:


synchronized 方法启用一个简单的
策略来防止线程
干扰和内存一致性
错误:如果一个对象可见
多个线程,所有读取或
写入该对象的变量是通过同步方法完成的

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

简而言之: 如果有两个线程正在读取和写入相同的资源,比如名为 foo 的变量,则需要确保这些线程访问变量以原子的方式。如果没有 synchronized 关键字,您的线程1可能看不到更改线程2对 foo ,或者更糟糕的是,它可能只变了一半。这不是你逻辑上所期望的。

In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo, you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo, or worse, it may only be half changed. This would not be what you logically expect.

同样,这是Java中一个非平凡的话题。要了解更多信息,请在此处浏览有关SO和互联网的主题:

Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:

  • Concurrency
  • Java Memory Model

继续探索这些主题,直到名称 Brian Goetz与您大脑中的术语并发永久关联。

Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.

这篇关于'同步'是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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