snelzb
snelzb

Reputation: 157

Why is my multithreaded program executing sequentially?

The following program isn't supposed to be executing sequentially but it is still doing so.

class A extends Thread
{

    public void run()
    {
        for(int i=0; i<=5; i++)
        {
            System.out.println("Thread A : "+i);
        }
        System.out.println("exit from A");
    }
}

class B extends Thread
{
    public void run()
    {
        for(int j=0; j<=5; j++)
        {
            System.out.println("Thread B: "+j);
        }
        System.out.println("exit from B");
    }
}

class C extends Thread
{
    public void run()
    {
        for(int k=0; k<=5; k++)
        {
            System.out.println("Thread C : "+k);
        }
        System.out.println("exit from C");
    }
}

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

The output I am getting is :

Thread A start
Thread A : 1
Thread A : 2
Thread A : 3
Thread A : 4
Thread A end
Thread B start
Thread B : 1
Thread B : 2
Thread B : 3
Thread B : 4
Thread B end
Thread C start
Thread C : 1
Thread C : 2
Thread C : 3
Thread C : 4
Thread C end

Can you please tell me why the execution is this way? Isn't the execution supposed to be sequential only when run

Upvotes: 1

Views: 208

Answers (3)

sohan nohemy
sohan nohemy

Reputation: 615

When new A().start() is called, a new thread is created and starts execution. Then new A().start() returns. When new B().start() is called a thread is being created. Within this time thread A will finish up execution and return because new Thread creation is a costly and blocking call. The same thing happens to thread C because thread B already finish up before Thread C starts executing. So they are still executing in parallel. But one is finishing up before next one starts up. Try to start A, B and C in parallel not sequentially as you did above. Then you may be able to see different result.

Upvotes: 2

Prim
Prim

Reputation: 2978

Creating and starting a thread have a cost in performance, it is not a simple light operation. In consequence, it consumes some resources.

In your example, your run methods are very simple (a loop over 5 int for printing). This code is very light and execution is very quick.

I think that the execution of each loop exited before the next thread was created. Try to add a Thread.sleep() into the loop, increase the number of increments, or do some more complex stuff.

Upvotes: 2

The threads do so little work that they finish before the switch to the next thread.

Try increasing the loops to 100000 or more.

Upvotes: 3

Related Questions