加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 主线程什么时候死?

发布时间:2020-12-15 00:50:17 所属栏目:Java 来源:网络整理
导读:问题是使用线程生成1到99之间的随机数.不过这里的问题是我不知道“主线程停止”从何而来? 主线是不是最终死了? 这是示例输出: Main thread stoppingRandom no = 57Random no = 47Random no = 96Random no = 25Random no = 74Random no = 15Random no = 46
问题是使用线程生成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,所以您对相对排序没有任何保证.来自两个不同线程的Println可以以任何方式显示交错……它恰好首先显示主线程的输出.

正如Alexis Leclerc指出的那样 – 你会得到一个不可预测的交错,就像在这个java threads tutorial中一样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读