use*_*892 7 java multithreading
问题是使用线程生成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
Run Code Online (Sandbox Code Playgroud)
神话类:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
主要课程:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
您不能依赖主线程和其他线程写入 System.out 的顺序。您的线程 t 执行得很好,主线程等待它完成,然后主线程退出,一切都按预期进行。但这并没有反映在您在 System.out 上看到的顺序中。
直接回答你的问题 - 主线程等待线程完成,然后向 System.out 写入一条消息,然后死亡。唯一令人困惑的是,因为您是从两个不同的线程写入 System.out,所以无法保证相对顺序。来自两个不同线程的 Println 可以以任何方式交错显示......它恰好首先与主线程的输出一起显示。
正如 Alexis Leclerc 指出的那样 - 您会得到不可预测的交错,与本java 线程教程中的相同。