简体   繁体   中英

Threads Execution

Is it possible to know when the thread has completed its execution without using any of the builtin function like isAlive, join. Suppose we have 3 threads A, B and C running in parallel. So how to know whether all the threads have completed their execution.

You can use CountDownLatch to help you out with it. Let's say you're making threads with ExecutorService, so you could make something like

        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

And in your ClassName you should have something like this:

class ClassName implements Runnable
{
    private CountDownLatch latch;

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

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

        latch.countDown();
    }
}

So in your run-method in ClassName, you need to call latch.countDown().

CountDownLatch is automatically syncronized, so you don't need to think about that.

You don't need to use ExectuorService in order to use Latch, this was just an example.

Well, since you're practically asking for bad ideas, here's a backwards, nondeterministic solution:

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!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM