gpt4 book ai didi

java - 同时运行多个线程然后运行主线程

转载 作者:行者123 更新时间:2023-11-30 07:14:57 25 4
gpt4 key购买 nike

我必须 || 运行多个线程,并在执行完所有这些线程后主线程继续。比如我有1个主线程和3个子线程,我的需求是

run main thread
pause main thread
run all 3 sub threads ||ly
after complition resume main thread

我创建了一个类 extends Thread 并调用了所有这些线程的启动方法,但这并没有解决我的问题。

我的代码:

for (MyThread myThread : myThreads) {
myThread.start();
}

感谢您的帮助。

最佳答案

尝试使用 Thread.join();

public class ThreadDemo implements Runnable {

public void run() {

Thread t = Thread.currentThread();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}

public static void main(String args[]) throws Exception {

Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
}

输出:

Thread-0, status = true
Thread-0, status = false

这是一个stack-over-flow link供引用。

关于java - 同时运行多个线程然后运行主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com