Thursday, 10 December 2020

Multithread-synchornized Monitor object

public void add(int value){

    synchronized(this){

       this.count += value;   

    }

  } 

Notice how the Java synchronized block construct takes an object in parentheses. In the example "this" is used, which is the instance the add method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object.


below using class level lock

public void add(int value){

    synchronized(Data.class){

       this.count += value;   

    }

  } 


In below code thread run one by one, once a thread complete his work then another will start due to lock on same string value "abc", then the compiler might actually use the same String object behind the scenes. 

 void method1(String threadName){
         synchronized ("abc") {
             System.out.println(threadName + ":method 1 running");
             try {
                 Thread.sleep(2000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
             System.out.println(threadName + ":sleep over");
             method2(threadName);
         }
    }

      void method2(String threadName){
        synchronized ("abc"){
        System.out.println(threadName+":method 2 running");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(threadName+":sleep over");
    }}

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...