zoukankan      html  css  js  c++  java
  • 《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.
  • 相关阅读:
    stax(和dom4j功能一样,这个是基于流的一种处理方式)
    JAXB(xml和对象的转换)
    wsdl理解
    webservice心得
    ZT 分智网博客 – 职场、面试技巧、职业规划
    discern concern fifth sixth
    ZT I Believe I Can Fly(我相信我能飞)
    ZT 理解class.forName()
    ZT 第9章 Framework的启动过程
    android 智能指针的学习先看邓凡平的书扫盲 再看前面两片博客提升
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3695147.html
Copyright © 2011-2022 走看看