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.

有帮助吗?

解决方案

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.

其他提示

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.

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top