HeXMaN
HeXMaN

Reputation: 123

Why doesn't my multithreaded Java code give a sequential output?

I started learning about multithreading recently. I tried the following code:

class AThread extends Thread {
    int input;

    public AThread(int y) {
        input=y;
    }

    public void compute() {
        System.out.println(input*input);
    }

    public void run() {
        compute();
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AThread a=new AThread(1);
        AThread b=new AThread(2);
        AThread c=new AThread(3);
        a.start();
        b.start();
        c.start();
    }
}

OUTPUT

Sometimes I get

4
1
9

But other times,

1
9
4

Why does this happen? I am still a rookie. Please answer in my standards.

Upvotes: 1

Views: 142

Answers (3)

Mike
Mike

Reputation: 2463

You are doing multiple things at once. The order the CPU executes is unspecified unless you synchronize manually.

Upvotes: 0

asteri
asteri

Reputation: 11572

When you create new Threads and start them, you leave the order of execution up to the JVM (Java Virtual Machine -- the enrvironment that all Java programs run in). This is analogous to forking processes at the operating system layer. You give up any control of sequential processing, and the job scheduler allows the various threads/processes CPU time as it sees fit.

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Because that's what multithreading is: do stuff in paralell; the relative order of threads is unspecified unless you synchronize manually.

It's in your book.

Upvotes: 9

Related Questions