Mahesh Gupta
Mahesh Gupta

Reputation: 55

Why threads are executing sequentially?

Q.1 I am trying to run two threads concurrently but here it is printing the value sequentially. For example it is printing 0 then 1 again 0 then 1. If threads are running concurrently then shouldn't it print like 0 0 then 1 1.

Q.2 it is giving output like 10, 11 then 0, 1, 0, 1. When it is printing 10 and 11 first. Does it mean that the threads t1 and t2 haven't started yet even though the program control goes to t1.start() and t2.start() first.

public class Main implements Runnable
{
    int x;

    public void run()
    {
        for(int i = 0; i < 2; i++)
        {
            System.out.println(x++);
        }
    }

    public static void main(String[] args)
    {
        Thread t1 = new Thread(new Main());

        Thread t2 = new Thread(new Main());

        t1.start();
        t2.start();

        int y = 10;
        for(int i = 0; i < 2; i++)
        {
            System.out.println(y++);
        }
    }
}

Upvotes: 1

Views: 179

Answers (2)

Mebin
Mebin

Reputation: 109

If you want to see the concurrency in action, placing the sleep() method somewhere in the run method should help.

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

The x variable used by the Threads is not the same x variable that is printing within the main method.

As the code executed in the Threads is so short the first Thread will have finished by the time that the second thread has started

Also with this trivial example your code will be affected by the output buffer as well.

Upvotes: 3

Related Questions