Java多线程-3 线程同步之synchronized

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.
Race condition
如果多个线程共享对象,且多个线程对共享对象的变量作修改时,竞争情况就可能发生了。

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.
什么意思呢?

  1. 官方说了:synchronized方法是为了防止线程之间互相干涉以及内存一致性错误:当一个对象对于多个线程可见时,所有对于这个对象变量的读和写必须通过synchronized 方法。
  2. 具体情况是:举个栗子–当你有2个线程读写同一个‘资源’,比如说一个名为 ‘foo’的变量, 你需要确保这些线程以一种原子操作访问该变量。如果没有用synchronized关键字,thread1可能看不到thread2对于变量’foo’所做的变化,更有甚者,thread1可能只看到了thread2对’foo’所作改变的一部分。这显然不是我们想要的结果!

  3. 少年,努力吧,等你达到了大佬“Brain Goetz”的高度,你就和并发合体了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值