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 Java Program with class Rectangle having instance variable width, length, area and colour. Create methods like setData() and area().Create two object of Rectangle and compare their area and colour. If area and colour both are the same for the objects then display “Matching Rectangles”, otherwise display “Non matching Rectangle”.