Tuesday, 8 December 2020

Multi threading example - synchonized ,static

public class Test {

    public static void main(String[] args) {

        sample obj = new sample();


        t1 tt1 = new t1(obj);

        t2 tt2 = new t2(obj);

        tt1.start();

        tt2.start();

    }

}

//It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.

class sample{

    public synchronized static void m1(String name){

        System.out.println(name+":m1");

        try {

            Thread.sleep(2000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

    public synchronized void m2(String name){

        System.out.println(name+":m2");

        try {

            Thread.sleep(2000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}


class t1 extends  Thread{

    sample s;

    t1(sample s){

        this.s =s;

    }

    @Override

    public void run() {

        s.m1(Thread.currentThread().getName());

        s.m2(Thread.currentThread().getName());

    }

}


class t2 extends Thread{

    sample s;

    t2(sample s){

        this.s =s;

    }

    @Override

    public void run() {

        s.m2(Thread.currentThread().getName());

        s.m1(Thread.currentThread().getName());


    }

}

output: 

Thread-1:m2

Thread-0:m1

wait 2 second

Thread-0:m2

Thread-1:m1 


or

Thread-0:m1

Thread-1:m2

wait 2 second

Thread-0:m2

Thread-1:m1

No comments:

Post a Comment

links for Data Structure

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