java - 等待线程

标签 java multithreading wait

我有一个包含以下 (Java) 代码的方法:

doSomeThings();
doSomeOtherThings();

doSomeThings() 创建一些线程,每个线程只会运行有限的时间。问题是我不希望在 doSomeThings() 启动的所有线程完成之前调用 doSomeOtherThings()。 (此外 doSomeThings() 将调用可能启动新线程等的方法。我不想在所有这些线程完成之前执行 doSomeOtherThings()。)

这是因为 doSomeThings() 等会将 myObject 设置为 null,而 doSomeOtherThings() 调用 myObject.myMethod() 并且我不希望 myObject 当时为 null

有没有一些标准的方法来做这种事情(在 Java 中)?

最佳答案

您可能想看看 java.util.concurrent 包。特别是,您可能会考虑使用 CountDownLatch

package de.grimm.game.ui;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

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

    final ExecutorService executor = Executors.newFixedThreadPool(5);
    final CountDownLatch latch = new CountDownLatch(3);

    for( int k = 0; k < 3; ++k ) {

        executor.submit(new Runnable() {
            public void run() {
                // ... lengthy computation...
                latch.countDown();
            }
        });
    }

    latch.await();

    // ... reached only after all threads spawned have
    // finished and acknowledged so by counting down the
    // latch.

    System.out.println("Done");
}
}

显然,这种技术只有在您事先知道 fork 线程的数量的情况下才有效,因为您需要使用该数量初始化锁存器。

另一种方法是使用条件变量,例如:

boolean done = false;

void functionRunInThreadA() {

    synchronized( commonLock ) {

        while( !done ) commonLock.wait();
    }

    // Here it is safe to set the variable to null
}

void functionRunInThreadB() {

    // Do something...

    synchronized( commonLock ) {
        done = true;
        commonLock.notifyAll();
    }
}

您可能需要添加异常处理(InteruptedException)等。

关于java - 等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2580691/

相关文章:

python - 使用 Python 子进程运行 SLURM 脚本将多个长作业提交到队列并等待作业完成,然后再继续 python 脚本

java - 使用同步但结果 IllegalMonitorStateException 从另一个类通知线程

java - JAX-RS 和 AngularJS 之间的请求和响应

java - Java线程同步问题

java - LinkedBlockingQueue 仅返回多个线程之一

C++ 多线程错误和 SOCKET

multithreading - 如何优化验证异步代码的测试?

java - 编程语言到处都一样吗?

java - 如何使用 JPA2 在 DDL 中为派生标识符指定生成的列名称?

android - android 线程中的 wait() 和 notify()