Synchronized block and monitor objects

前端 未结 3 511
名媛妹妹
名媛妹妹 2021-02-08 15:19

Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used \"this\" as a mon

3条回答
  •  独厮守ぢ
    2021-02-08 15:58

    if the in the following code the synchronized code will restrict access to the threads

    Yes. The block cannot be invoked concurrently more then once on the same String object [and actually, all blocks which are syncrhonized on this String object].

    how is it different from, if we have used "this" as a monitor object instead of "msg"

    synchronized(this) prevents concurrent access to all blocks by the same object, in this case, the object that is the this of the method, will not be able to go into the synchronised block twice.

    for example [using java-like pseudo code]:

    s1 = s2;
    Thread1:
    MyObject o = new MyObject();
    o.display(s1);
    Thread2:
    MyObject o = new MyObject();
    o.display(s2);
    

    The current method will not allow the block to be invoked concurrently by Thread1 and Thread2

    However:

    MyObject o = new MyObject();
    Thread1:
    o.display("s1");
    Thread2:
    o.display("s2");
    

    Will not show blocking behavior between them - the monitor is catched by each "s1" and "s2" without disturbing each other.

提交回复
热议问题