Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

java - Multithread output not expected

I am new to Java and the concept of multi-threading. Here's my experimental code:

public class Multithread implements Runnable {

    Thread t;

    public Multithread(int prior, String name) {
        this.t = new Thread(this, name);
        this.t.setPriority(prior);
        this.t.start();
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            if (this.t.getName().equals("thread1")) {
                System.out.println("First Child Thread Loop No " + i);
            }
            else {
                System.out.println("Second Child Thread Loop No " + i);
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        new Multithread(10, "thread1");
        new Multithread(7, "thread2");
    }
}

The output is:

First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
Second Child Thread Loop No 3
First Child Thread Loop No 3
Second Child Thread Loop No 4
First Child Thread Loop No 4
Second Child Thread Loop No 5
First Child Thread Loop No 5

Well I expected to be a simple as this:

First Child Thread Loop No 1
Second Child Thread Loop No 1
First Child Thread Loop No 2
Second Child Thread Loop No 2
First Child Thread Loop No 3
Second Child Thread Loop No 3
First Child Thread Loop No 4
Second Child Thread Loop No 4
First Child Thread Loop No 5
Second Child Thread Loop No 5

I expect first thread to get executed always before the second thread. Please explain my output. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason for that is when threads start running you cannot guess the order of their appearing, very basic threads issue - you can read: http://www.codeproject.com/Articles/616109/Java-Thread-Tutorial or http://www.vogella.com/articles/JavaConcurrency/article.html or any other basic Thread tutor. Good luck.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...