菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
53
0

《Cracking the Coding Interview》——第16章:线程与锁——题目6

原创
05/13 14:22
阅读数 468612

标签:com   class   blog   http   code   div   img   java   style   javascript   strong   

2014-04-27 20:25

题目:关于java中标有synchronized的成员方法?

解法:这代表同一个对象实例synchronized方法不能被多个线程同时调用。注意有这么多个地方都加粗了,如果这些条件有一个不满足的话,就是可以调用的。另外,如果此方法是静态成员方法, 那么总可以认为是“同一实例”的,因为静态方法就属于一个类,类似于单体。

代码:

mamicode.com,码迷
 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.
mamicode.com,码迷

 

《Cracking the Coding Interview》——第16章:线程与锁——题目6,码迷,mamicode.com

《Cracking the Coding Interview》——第16章:线程与锁——题目6

发表评论

0/200
53 点赞
0 评论
收藏
为你推荐 换一批