线程执行

时间:2016-04-22 00:33:07

标签: java multithreading

是否可以在不使用任何内置函数(如isAlive,join)的情况下知道线程何时完成执行。 假设我们有3个并行运行的线程A,B和C.那么如何知道所有线程是否都已完成执行。

2 个答案:

答案 0 :(得分:0)

您可以使用CountDownLatch来帮助您解决问题。 我们假设您正在使用ExecutorService创建线程,因此您可以制作类似

的内容
        CountDownLatch latch = new CountDownLatch(threadsCount);
        ExecutorService executor = Executors.newFixedThreadPool(threadsCount);

        for (int x = 0; x < threadsCount; x++)
        {
            executor.submit(new ClassName(latch));
        }
        try
        {
            latch.await();
        }
        catch (Exception ignored){} 
//all threads are done at this point

在你的ClassName中你应该有这样的东西:

class ClassName implements Runnable
{
    private CountDownLatch latch;

    //constructor:
    ClassName(CountDownLatch latch)
    {
         this.latch = latch;
    }

    //run method:
    @Override
    void run()
    {
        //Your thread code...

        latch.countDown();
    }
}

因此,在ClassName的run-method中,需要调用latch.countDown()。

CountDownLatch会自动同步,因此您无需考虑这一点。

您不需要使用ExectuorService来使用Latch,这只是一个例子。

答案 1 :(得分:0)

好吧,既然你实际上是在寻求不好的想法,那么这是一个倒退的,不确定的解决方案:

public static void main(String[] args) {
    Thread t1 = new Thread(() -> System.out.println("t1"));
    t1.start();
    WeakReference<Thread> r1 = new WeakReference<Thread>(t1);
    t1 = null;

    Thread t2 = new Thread(() -> System.out.println("t2"));
    t2.start();
    WeakReference<Thread> r2 = new WeakReference<Thread>(t2);
    t2 = null;

    while (r1.get() != null || r2.get() != null) {
        System.gc();
    }

    System.out.println("done!");
}
相关问题