Java多线程-3 线程同步之synchronized
2017-06-03 20:34
459 查看
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含义
来自stackoverflow的问题及回答: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”的高度,你就和并发合体了
相关文章推荐
- Java多线程的线程同步需要注意的地方synchronized与static synchronized区别
- Java 多线程(四)——线程同步(synchronized、ReentrantLock)
- java多线程之synchronized(线程同步)
- Java线程,多线程,线程同步,以及Java回调线程,还有难懂的synchronized
- Java多线程(二):线程同步synchronized和volatile
- 多线程拨号Java版(探讨synchronized和Lock线程同步)
- java 多线程(4) 线程同步之锁(synchronized) / 死锁 / 两个锁定对象期间访问(修改)其变量的面试
- JAVA学习笔记--多线程(三)synchronized实现线程同步
- Java 多线程(四)——线程同步(synchronized、ReentrantLock)
- Java 多线程(四)——线程同步(synchronized、ReentrantLock)
- Java多线程:线程同步与关键字synchronized
- 【Java多线程】-线程同步synchronized和volatile
- Java:多线程,线程同步,synchronized关键字的用法(同步代码块、非静态同步方法、静态同步方法)
- Java多线程:线程同步与关键字synchronized
- Java多线程,线程同步synchronized,线程死锁【线程池常规用法】多线程并发处理
- Java【多线程知识总结(7)】多线程同步问题-关于synchronized代码块和synchronized方法的应用
- 如何使用java synchronized进行线程同步
- 如何使用java synchronized进行线程同步
- java多线程总结四:volatile、synchronized示例
- Java多线程总结之由synchronized说开去