Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

java - “同步”是什么意思?(What does 'synchronized' mean?)

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

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

  • What is the significance of the synchronized keyword?

    (synchronized关键字的意义是什么?)

  • When should methods be synchronized ?

    (方法应何时synchronized ?)

  • What does it mean programmatically and logically?

    (从程序上和逻辑上是什么意思?)

  ask by Johanna translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources.

(synchronized关键字是关于不同线程读写相同变量,对象和资源的全部内容。)

This is not a trivial topic in Java, but here is a quote from Sun:

(这不是Java中的琐碎话题,但以下是Sun的引文:)

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.

(synchronized方法提供了一种防止线程干扰和内存一致性错误的简单策略:如果一个对象对多个线程可见,则对该对象变量的所有读取或写入都将通过同步方法完成。)

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.

(简而言之:当您有两个线程正在读取和写入同一个“资源”时,说一个名为foo的变量,您需要确保这些线程以原子方式访问该变量。)

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.

(如果没有synchronized关键字,线程1可能看不到对foo进行的更改线程2,或者更糟的是,它可能只更改了一半。)

This would not be what you logically expect.

(这在逻辑上不会是您所期望的。)

Again, this is a non-trivial topic in Java.

(同样,这是Java中不平凡的主题。)

To learn more, explore topics here on SO and the Interwebs about:

(要了解更多信息,请在SO和Internet上探索有关以下主题:)

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

(继续探索这些主题,直到名称“ Brian Goetz”与大脑中的“并发”一词永久关联。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...