首页 > 代码库 > 《Cracking the Coding Interview》——第16章:线程与锁——题目6
《Cracking the Coding Interview》——第16章:线程与锁——题目6
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.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。