1. synchronized解决的问题
If two or more threads share an object, and more than one thread updates variables in that shared object, race conditions may occur.
如果多个线程共享对象,且多个线程对共享对象的变量作修改时,竞争情况就可能发生了。
2. synchronized含义
Q:What does ‘synchronized’ mean?
A: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 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.
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.
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
Keep exploring these topics until the name “Brian Goetz” becomes permanently associated with the term “concurrency” in your brain.
什么意思呢?
- 官方说了:synchronized方法是为了防止线程之间互相干涉以及内存一致性错误:当一个对象对于多个线程可见时,所有对于这个对象变量的读和写必须通过synchronized 方法。
具体情况是:举个栗子–当你有2个线程读写同一个‘资源’,比如说一个名为 ‘foo’的变量, 你需要确保这些线程以一种原子操作访问该变量。如果没有用synchronized关键字,thread1可能看不到thread2对于变量’foo’所做的变化,更有甚者,thread1可能只看到了thread2对’foo’所作改变的一部分。这显然不是我们想要的结果!
少年,努力吧,等你达到了大佬“Brain Goetz”的高度,你就和并发合体了