문제

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