Write a program in Java to demonstrate use of synchronization of threads when multiple threads are trying to update common variable.


AIM: Write a program in Java to demonstrate the use of synchronization of threads when multiple threads are trying to update common variables.

CODE:

class Test{

            void call(String msg){

                        System.out.print("\n["+msg);

                        try{

                                    Thread.sleep(100);

                        }

                        catch(InterruptedException e){

                                    System.out.println(e);

                        }

                        System.out.println("]");

            }

}

class demoThread extends Thread{

            Test c;

            String msg;

            demoThread(Test c, String msg){

                        this.c=c;

                        this.msg=msg;

            }

            public void run(){

                        synchronized(c){

                                    c.call(msg);

                        }

            }

}

 

class p32{

            public static void main(String args[]){

                        Test c = new Test();

                        demoThread dt1 = new demoThread(c,"Hiii");

                        System.out.println("\ndemoThread  1: "+dt1);

                       

                        demoThread dt2 = new demoThread(c,"Hello");

                        System.out.println("\ndemoThread  2: "+dt2);

                       

                        demoThread dt3 = new demoThread(c,"World!!");

                        System.out.println("\ndemoThread  3: "+dt3);

                       

                        dt1.start();

                        dt2.start();

                        dt3.start();

            }

}

OUTPUT:



Comments

Popular posts from this blog

Write an application that illustrates method overriding in the same package and different packages. Also demonstrate accessibility rules in inside and outside packages

Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, and Circle. Define one method area()in the abstract class and override this area() in these three subclasses to calculate for specific object.

Write a program that illustrates interface inheritance. Interface P12 inherits from both P1 and P2. Each interface declares one constant and one method. The class Q implements P12. Instantiate Q and invoke each of its methods. Each method displays one of the constants.