• 《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.
  • 相关阅读:
    文件处理(记录经典代码及相关逻辑)
    python与pip在widow下cmd命令行操作问题收集:python、pip不是内部或外部命令,也不是可运行程序
    python—函数中存在的部分问题
    python —匿名函数(lambda)
    Python—递归函数
    python-函数参数
    python代码运行过程
    String类练习
    String类的常用方法
    死锁与进程通信
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3695147.html
Copyright © 2020-2023  润新知