gpt4 book ai didi

java - 我们如何在Java中调用多线程?

转载 作者:行者123 更新时间:2023-12-03 12:48:19 24 4
gpt4 key购买 nike

有没有办法在另一个线程完成工作后调用一个线程?我只想在前一个线程的工作完成时背对背调用三个线程。

我正在尝试这个

public class TestThreads {
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread first = new Thread(r);
Thread second = new Thread(r);
Thread third = new Thread(r);
first.start();
second.start();
third.start();
}
}

这是正确的方法吗??

最佳答案

您正在寻找Thread.Join()

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

Like sleep, join responds to an interrupt by exiting with an InterruptedException.

那就是

first.start();
first.join();
second.start();
second.join();
third.start();

在旁注中,您可以引用此 Thread join() method in Java with example

关于java - 我们如何在Java中调用多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230472/

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