Java多线程-3 线程同步之synchronized
来源:互联网 发布:怎样关闭136端口 xp 编辑:程序博客网 时间:2024/06/11 05:01
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多线程-3 线程同步之synchronized
- java多线程之synchronized(线程同步)
- Java基础-多线程-③线程同步之synchronized
- Java基础-多线程-③线程同步之synchronized
- Java基础-多线程-③线程同步之synchronized
- java线程同步之synchronized
- java线程之同步synchronized
- 多线程03--线程同步之synchronized
- Java多线程:线程同步与关键字synchronized
- 【Java多线程】-线程同步synchronized和volatile
- java线程多线程同步机制(synchronized)
- Java多线程同步总结之synchronized
- 【JAVA】多线程之synchronized 同步数据 方法
- JAVA并发编程3_线程同步之synchronized关键字
- java并发编程-线程同步之synchronized
- 多线程之同步Synchronized
- java Synchronized 多线程同步
- java多线程同步,Synchronized
- C语言数据结构——二叉树的顺序存储结构
- 【机房重构】-泛型与datatable
- 将mysql的查询结果保存到文件中
- MYSQL Identifying relationship 和non-Identifying relationship 区别。
- MapReduce——LongWritable cannot be cast to org.apache.hadoop.io.Text 错误原因
- Java多线程-3 线程同步之synchronized
- Swift计算属性和存储属性的重要区别
- python批量下载美女图片
- 【FCN实践】02 模型迁移及初始化
- leetcode572. Subtree of Another Tree
- Ubuntu新建用户组
- 《C陷阱与缺陷》读书笔记
- c++编译与链接
- 计算表达式