等待线程

Pau*_*ers 4 java multithreading wait

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

doSomeThings();
doSomeOtherThings();
Run Code Online (Sandbox Code Playgroud)

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

这是因为doSomeThings(),除其他事项外将设置myObjectnull,而doSomeOtherThings()电话myObject.myMethod(),我不希望myObjectnull在那个时候.

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

Dir*_*irk 10

您可能想要查看该java.util.concurrent包.特别是,您可以考虑使用CountDownLatchas in

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");
}
}
Run Code Online (Sandbox Code Playgroud)

显然,如果您事先知道分叉线程的数量,这种技术将起作用,因为您需要使用该数字初始化锁存器.

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*ams 6

看看Thread.join()方法.

我不清楚你的确切实现,但似乎doSomeThings()应该在返回之前等待子线程.

在doSomeThings()方法内部,通过调用Thread.join()方法等待线程.

当您创建一个线程并调用该线程的join()方法时,调用线程将等待该线程对象死亡.

例:

// Create an instance of my custom thread class
MyThread myThread = new MyThread();
// Tell the custom thread object to run
myThread.start();
// Wait for the custom thread object to finish
myThread.join();
Run Code Online (Sandbox Code Playgroud)