Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...