Sunday, 29 July 2018

synchronized Method and block

Problem without Synchronization

package threads;


public class Two {
    public static void main(String args[]) {
        One obj = new One();
        Thread th1 = new Thread(new t1(obj));
        Thread th2 = new Thread(new t2(obj));
        th1.start();
        th2.start();
    }
}

class t1 implements Runnable{
   
    One one;
    public t1(One one) {
     this.one = one;
    }
    @Override
    public void run() {
             one.add();
    }
   
}

class t2 implements Runnable{
    One one;
    public t2(One one) {
     this.one = one;
    }
    @Override
    public void run() {
             one.add();
    }
   
}



package threads;


public class One {
    int count;
    public void add() {
        for(int i=0;i<5;i++) {
            this.count =get()+1;
            System.out.println(count);
             try{ 
                  Thread.sleep(400); 
                 }catch(Exception e){System.out.println(e);} 
               }
        }

    public int get() {
        return count;
    }
}



output:

2
1
3
4
5
6
7
8
9
9


Note: every time we will get different output.


Solution with  Synchronization

change in class one as below:

package threads;


public class One {
    int count;
    public synchronized void add() {
        for(int i=0;i<5;i++) {
            this.count =get()+1;
            System.out.println(count);
             try{
                  Thread.sleep(400);
                 }catch(Exception e){System.out.println(e);}
               }
        }

    public int get() {
        return count;
    }
}


Now out put is below:
1
2
3
4
5
6
7
8
9
10

Use synchronized block:

public void add() {
        for(int i=0;i<5;i++) {
            synchronized (this) {
                this.count =get()+1;
                System.out.println(count);
            }

             try{ 
                  Thread.sleep(400); 
                 }catch(Exception e){System.out.println(e);} 
               }
        }

output:
1
2
3
4
5
6
7
8
9
10


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( One obj = new One();). The object taken in the parentheses by the synchronized construct is called a monitor object. 



No comments:

Post a Comment

links for Data Structure

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