“同步”是什么用Java表示? [英] What does "synchronized" mean in Java?

查看:157
本文介绍了“同步”是什么用Java表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力学习设计模式。 此网站使用 synchronized 关键字,但我不明白它的作用。

I have been trying to learn design patterns. This site uses the synchronized keyword, but I don't understand what it does.

我在网上搜索,发现它与多线程和内存有些关系,但我是机械的工程师并不明白这意味着什么。

I searched on the net and found that it is somewhat related to multi-threading and memory, but I am a mechanical engineer and don't understand what that means.

有人可以帮我理解线程和 synchronized 关键字吗?

Can anybody please help me understand threads and the synchronized keyword?

推荐答案

C ++中没有 synchronized 关键字。

There is no synchronized keyword in C++.

但是Java中有一个方法它表示以下两件事

There is one in Java, though, where for methods it means the following two things:



  • 不可能两个同步方法的调用对同一个对象进行交错。当一个线程正在为一个对象执行一个synchronized方法时,所有其他线程都会调用同一个对象的同步方法阻塞(暂停执行),直到第一个线程完成该对象为止。

  • 当一个synchronized方法退出,它会自动建立一个before-before关系,同时对同一个对象的同步方法进行任何后续调用。这可以保证对所有线程都可以看到对对象状态的更改。

类似的规则适用于任意块

另外,我建议从同行评审的书中学习,而不是一些任意的非权威性网站。

Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.

这篇关于“同步”是什么用Java表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆