Menu
Topics Index
...
`

ThreadProgramming - Java Example Program


ThreadProgramming
class MainClass
{
    public static void main(String[] args)
    {
        CounterClass thread1 = new CounterClass(); // LINE A
        thread1.start();
        CounterClass thread2 = new CounterClass();
        thread2.start();
        CounterClass thread3 = new CounterClass();
        thread3.start();
    }
}

class CounterClass extends Thread
{
    public void run()
    {
        this.increment(); // LINE B
    }

    void increment()
    {
        System.out.println("ThreadStatus: " + Thread.currentThread().getName() + " entered "); // LINE C
        for (int i = 0; i < 3; i++)
        {
            System.out.println("value of i " + i);
            try
            {
                Thread.sleep(200); // LINE D
            }
            catch (Exception e)
            {
                System.out.println("Thread Interrupted.");
            }
        }
        System.out.println("ThreadStatus: " + Thread.currentThread().getName() + "  exiting."); // LINE E
    }
}
OUTPUT

ThreadStatus: Thread-1 entered
value of i 0
ThreadStatus: Thread-0 entered
value of i 0
ThreadStatus: Thread-2 entered
value of i 0
value of i 1
value of i 1
value of i 1
value of i 2
value of i 2
value of i 2
ThreadStatus: Thread-1  exiting.
ThreadStatus: Thread-0  exiting.
ThreadStatus: Thread-2  exiting.

DESCRIPTION

At LINE A we are creating three objects for CounterClass which acts like threads and starting them by invoking thread start method. At LINE B we are calling increment method. At LINE C we are printing the thread name by using getName method. At LINE D we are making the thread to sleep for 200 milliseconds. At LINE E we are printing the thread leaving statement.

THINGS TO TRY
  • Create one more thread thread4 to CounterClass and run it.
  • Modify the increment method such that it also prints thread's priority.

© meritcampus 2019

All Rights Reserved.

Open In App