问题是使用线程生成1到99之间的随机数.不过这里的问题是我不知道“主线程停止”从何而来?
主线是不是最终死了?
主线是不是最终死了?
这是示例输出:
Main thread stopping Random no = 57 Random no = 47 Random no = 96 Random no = 25 Random no = 74 Random no = 15 Random no = 46 Random no = 90 Random no = 52 Random no = 97 Thread that generates random nos is stopping
神话类:
public class MyThread extends Thread {
MyThread() {
// default constructor
}
MyThread(String threadName) {
super(threadName); // Initialize thread.
start();
}
public void run() {
// System.out.println(Thread.currentThread().getName());
Random rand = new Random();
int newValue;
for (int i = 0; i < 10; i++) {
newValue = rand.nextInt(99);// generates any vale between 1 to 99
System.out.println("Random no = " + newValue);
}
System.out.println("Thread that generates random nos is stopping");
}
}
主要课程:
public class HW5ex2a {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join();// wait for the thread t to die
System.out.println("Main thread stopping");
}
}
解决方法
您不能依赖主线程和其他线程写入System.out的顺序.
你的线程执行正常,主线程等待它完成然后主线程退出,所有都按预期.但这不会反映在System.out上看到的顺序中.
你的线程执行正常,主线程等待它完成然后主线程退出,所有都按预期.但这不会反映在System.out上看到的顺序中.
要直接回答你的问题 – 主线程等待线程完成,然后它将消息写入System.out,然后它就会死掉.唯一令人困惑的是,因为您从两个不同的线程写入System.out,所以您对相对排序没有任何保证.来自两个不同线程的Println可以以任何方式显示交错……它恰好首先显示主线程的输出.
正如Alexis Leclerc指出的那样 – 你会得到一个不可预测的交错,就像在这个java threads tutorial中一样.