java如何另开一个线程去播放其他音效,如何在java中加入一个线程与其他线程?...

本文讨论了如何在Java中使用join()方法确保主线程在所有子线程完成执行后才继续运行。主要内容包括在启动子线程后调用join()的重要性,以及如何在所有线程结束后输出提示信息。正确的做法是在启动子线程后调用join(),以等待所有线程执行完毕,避免主线程提前结束。
摘要由CSDN通过智能技术生成

I have one main thread that starts 10 other threads. I want that the main thread will be finished only after all other threads stopped. So should I call join() on other 10 threads before starting or after starting them. For instance:

// in the main() method of Main thread

Thread [] threads = new Thread[10];

for(int i = 0; i < 10; i++) {

// ParserThread() is a runnable thread

threads[i] = new Thread(new ParserThread());

threads[i].join();

threads[i].start();

}

System.out.println("All threads have been finished"); // line no. 9

So as in the above example, should i call join() before start() or after start().

Will the control returns to line no. 9 only after all the threads have finished.

When the run method of any thread has been executed, then will that thread die or remain alive. If it will, the how to die all the threads when their run method has finished means when the control returns to line no. 9

解决方案

Calling join() on a thread only makes sense after the thread is started. The caller of join() will stop and wait until the other thread finishes what it's doing. So you may want to do this:

// in the main() method of Main thread

Thread [] threads = new Thread[10];

for(int i = 0; i < 10; i++) {

// ParserThread() is a runnable thread

threads[i] = new Thread(new ParserThread());

threads[i].start();

}

System.out.println("All threads have been started");

for(int i = 0; i < 10; i++) {

threads[i].join();

}

System.out.println("All threads have been finished");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值