2014-04-27 20:25
题目:关于java中标有synchronized的成员方法?
解法:这代表同一个对象实例的synchronized方法不能被多个线程同时调用。注意有这么多个地方都加粗了,如果这些条件有一个不满足的话,就是可以调用的。另外,如果此方法是静态成员方法, 那么总可以认为是“同一实例”的,因为静态方法就属于一个类,类似于单体。
代码:
1 // 16.6 How do you explain the "synchronized" keyword? 2 There're three properties about a member method of a class: 3 1. static or not 4 2. synchronized or not 5 3. of same object instance of a class or not 6 For example: 7 public class FooBar { 8 public void f() {}; 9 public synchronized void g() {}; 10 public static synchronized void h() {}; 11 } 12 13 There're three member methods in the class FooBar: 14 1. f() is non-static and unsynchronized. 15 2. g() is non-static and synchronized. 16 3. h() is static and synchronized. 17 18 The keyword "synchronized" makes sure that an instance of code segment is executed by only one thread at a time. 19 The instance of the code segment may be a static one, or a non-static one belonging to one object instance. 20 21 Unsynchronized methods is free of these constraints. They can be called by arbitrary numbers of threads at the same time. 22 Synchronized methods of different object instances is independent from each other. They can be called by different threads at the same time. 23 24 Here's a truth table for your information: 25 ---------------------------------------------------------------- 26 synchronized|static |sameinstance |can be called at same time? 27 0 |0 |0 |1 28 0 |0 |1 |1 29 0 |1 |0 |1 30 0 |1 |1 |1 31 1 |0 |0 |1 32 1 |0 |1 |0 33 1 |1 |0 |1 34 1 |1 |1 |0 35 ---------------------------------------------------------------- 36 Plus: Static method can be regarded as singleton, thus it's always one instance only.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)