问题是使用线程生成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
Mythread class:
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");
}
}
答案 0 :(得分:2)
您不能依赖主线程和其他线程写入System.out的顺序。 你的线程执行正常,主线程等待它完成,然后主线程退出,所有都按预期。但是这并没有反映在System.out上看到的顺序。
直接回答你的问题 - 主线程等待线程完成,然后它将一条消息写入System.out,然后它就死了。唯一令人困惑的是,因为您从两个不同的线程写入System.out,所以您对相对排序没有任何保证。来自两个不同线程的Println可以以任何方式显示交错...它恰好首先显示主线程的输出。
正如Alexis Leclerc所指出的那样 - 你会得到一个不可预测的交错,就像在java threads tutorial中一样。
答案 1 :(得分:1)
由于两个线程都在不同的内核上运行(最有可能),因此每个内核(在L1缓存中)都会缓存线程可以访问的对象,以提高性能。
每当更改对象的状态时,所有缓存都会尝试与RAM中的值同步,这不能保证立即发生。
某些线程可能能够在其他线程之前进行同步,即使它违反了发生之前之间的关系。
这背后的原因在于java memory model。
的实施此处System.out
对象也发生了同样的事情。
您无法保证数据传递和刷新数据的顺序。
因此无法预测。致电
System.out.flush();
可能会改善结果,但不会保证。
有关更多信息,请参阅Multiple threads using System.out.println in Java
希望这有帮助。
答案 2 :(得分:0)
主线程退出以下情况: -
System.exit(1)
。希望它会对你有所帮助。