我是 Java 和多线程概念的新手。这是我的实验代码:
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");
}
}
输出是:
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
好吧,我希望是这样一个简单的:
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
我希望第一个线程总是在第二个线程之前执行。请解释我的输出。提前致谢。