Skip to main content

How to create Thread in Java?

Here, program illustrates the use of Thread class for creating and running threads in an application. The program creates three threads A, B and C for undertaking three different tasks. The main method in the amit class also constitutes another thread which we may call the main thread.

The main thread dies at the end of its main method. However, before it dies, it creates and starts all the three threads A, B, and C. Note the statements like

            new A().start();

in the main thread. This is just a compact way of starting a thread. This is equivalent to:
            A aobj = new A();
            aobj.start();

Immediately after the thread A is started, there will be two threads running in the program: the main thread and the thread A. The start() method returns back to the main thread immediately after invoking the run() method, this allowing the main thread to start the thread B. Similarly it starts C thread. By the time the main thread has reached the end of its main method, there are a total of four separate threads running in parallel.

We have simply initiated three new threads and started them. We did not hold on to them any further. They are running concurrently on their own. Note that the output from the threads are not specially sequential. They do not follow any specific order. They are running independently of one another and each executes whenever it has a chance. Remember, once the threads are started, we cannot decide with certainty the order in which they may execute statements.

Program:

class A extends Thread
{
            public void run()
            {
                        for (int i = 1; i < = 5; i++)
                        {
                                    System.out.println(“From Thread A: i = “ + i);
                        }
                        System.out.println(“Exit from A”);
            }
}

class B extends Thread
{
            public void run()
            {
                        for (int j = 1; j < = 5; j++)
                        {
                                    System.out.println(“From Thread B: j = “ + j);
                        }
                        System.out.println(“Exit from B”);
            }
}

class C extends Thread
{
            public void run()
            {
                        for (int k = 1; k < = 5; k++)
                        {
                                    System.out.println(“From Thread C: k = “ + k);
                        }
                        System.out.println(“Exit from C”);
            }
}

class amit
{
            public static void main(String args[])
            {
                        new A().start();
                        new B().start();
                        new C().start();
            }
}

Output:





Resources Used:

1. E Balagurusamy
2. Java in 60 minutes a day
3. Complete Reference
4. Teach Yourself

Compiled By: Chaudhary Amit V.

Comments