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

标签 java multithreading

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

我正在尝试这个

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/

相关文章:

java - JSON 反序列化抛出异常 - 无法从 START_OBJECT token 中反序列化 java.util.ArrayList 的实例

java - 包装 C++ 对象的最佳 JNI 模式?

c++ - 程序默默关闭

java - 以线程安全的方式更新ConcurrentHashMap

java - 有没有办法为 OpenNLP 获取 "original"文本数据?

java - Jetty URL 重写/重定向去除查询字符串

java - java main方法的执行创建了多少个线程?

Java/Scala多线程文件写入

java - Spring Batch - 在外部进程中完成处理时连接关闭

多个变量之间的java线程安全