问题描述
我对 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
方法实现了一个简单的防止线程的策略干扰和内存一致性错误:如果对象可见多个线程,所有读取或写入该对象的变量是通过同步方法完成.
简而言之:当您有两个线程正在读取和写入同一个资源"时,比如说一个名为 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 和 Internet 上探索以下主题:
Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:
继续探索这些主题,直到名称 Brian Goetz" 在您的大脑中与术语并发性" 永久关联.
Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.
这篇关于“同步"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!