Menu
Topics Index
...
`

ThreadWithRunnable - Java Example Program


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

class CounterClass implements Runnable
{

    Thread thread;

    public void run()
    {
        this.increment(); // LINE C
    }

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

    public void startThread()
    {
        thread = new Thread(this); // LINE B
        thread.start();
    }
}
OUTPUT

ThreadStatus: Thread-0 entered
value of i 0
ThreadStatus: Thread-1 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-0  exiting.
ThreadStatus: Thread-1  exiting.
ThreadStatus: Thread-2  exiting.

DESCRIPTION

At LINE A we are creating three objects for CounterClass. At LINE B in the startThread we are creating a Thread object every time when an object is created with the constructor Thread(Runnable object) and running it by invoking thread start method which in turn returns a call to thread run method. At LINE C in the run method we are calling increment method. At LINE D in the increment method we are printing thread name by using getName method . At LINE E we are making the thread to sleep for 200 milliseconds. At LINE F we are printing the statement thread leaving.

THINGS TO TRY
  • Create one more thread for the ThreadClass with String name as Thread-4
  • comment LINE B to see java.lang.NullPointerException since we cannot invoke start method on null thread.
  • At LINE B use the constructor Thread(Runnable object, String name) and give names to the threads.

© meritcampus 2019

All Rights Reserved.

Open In App