How to wait for a thread that spawns it's own thread?

前端 未结 3 1103
情书的邮戳
情书的邮戳 2020-12-07 01:37

I\'m trying to test a method that does it\'s work in a separate thread, simplified it\'s like this:

public void methodToTest()
{
    Thread thread = new Thre         


        
3条回答
  •  忘掉有多难
    2020-12-07 01:45

    Since your threads seems to be performing different operations, you can use CountDownLatch to solve your problem.

    Declare a CountDownLatch in main thread and pass this latch object to other threads. use await() in main thread and decrement latch in other threads.

    In Main thread: ( first thread)

    CountDownLatch latch = new CountDownLatch(2);
    /* Create Second thread and pass the latch. Pass the same latch from second 
       thread to third thread when you are creating third thread */
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

    Pass this latch to second and third threads and use countdown in these threads

    In second and third threads,

    try {
        // add your business logic i.e. run() method implementation
        latch.countDown();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

    Have a look this article for better understanding.

    ExecutorService invokeAll() API is other preferable solution.

提交回复
热议问题