Menu
Topics Index
...
`

ThreadSynchronization227 - Java Example Program


ThreadSynchronization227
class MainClass
{
    public static void main(String arg[])
    {
        ThreadClass Thread1 = new ThreadClass("Thread1");
        ThreadClass Thread2 = new ThreadClass("Thread2");
        ThreadClass Thread3 = new ThreadClass("Thread3");
        
        Thread1.start(); // LINE A
        Thread2.start();
        Thread3.start();    
    }
}

class ThreadClass extends Thread
{
    String threadname;

    ThreadClass(String threadname)
    {
        this.threadname = threadname;
    }

    synchronized void Incrementor()
    {
        System.out.println("Incrementor method invoked by " + this.threadname);
        for (int i = 1; i < 4; i++)
        {
            System.out.println("Icremented value of i : " + i);
        }
    }

    public void run()
    {
        this.Incrementor(); // LINE B

    }
}
OUTPUT

Incrementor method invoked by Thread1
Icremented value of i : 1
Icremented value of i : 2
Icremented value of i : 3
Incrementor method invoked by Thread2
Icremented value of i : 1
Icremented value of i : 2
Icremented value of i : 3
Incrementor method invoked by Thread3
Icremented value of i : 1
Icremented value of i : 2
Icremented value of i : 3

DESCRIPTION

In the above program there are two classes MainClass and ThreadClass. ThreadClass have a method by name Incrementor. we created three threads Thread1, Thread2 and Thread3 for ThreadClass. At LINE A we are invoking run method of the threads by calling the start method. At LINE B in run method we are invoking Incrementor method on each thread. Here the Incrementor method is synchronized so it allows one thread at a time so the above program produces the following output.

THINGS TO TRY
  • Remove the synchronized keyword for the method Incrementor in the ThreadClass and observe the output.

© meritcampus 2019

All Rights Reserved.

Open In App