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”与大脑中的“并发”一词永久关联。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…