gpt4 book ai didi

java - 并行线程需要到达某个点,等待另一个线程,然后继续执行-最佳方法?

转载 作者:行者123 更新时间:2023-12-03 13:18:33 25 4
gpt4 key购买 nike

这是(简化的)场景:

  • 我有并行运行的线程A,B,C。
  • 所有3个线程都到达其执行的第7步后,它们必须等待。 (每个线程将在不同的时间到达步骤7,这无法提前知道)。
  • 然后,线程D启动并运行完成。
  • 只有在D完成之后,A,B和C才能恢复并运行到完成。

  • 有什么好的工具或设计可以解决此问题?
    到目前为止,我看过的并发和信号量示例似乎只处理2个线程,或者假设并行线程在做类似的事情,但只共享一个var或消息传递。我还没有找到适合上述方案的任何方法。我将继续研究该问题,并将根据发现结果进行更新。
    如果CountDownLatch不需要退出其他线程,则可能会起作用。或者,如果它可以反向工作,则使 n线程等待直到线程D退出。
    我对并发还比较陌生(大学类(class)不会在需要的任何时间提供它),所以请多多包涵。如果有人对此问题有类似的疑问,请将此链接放在这里: HowToDoInJava - Concurrency

    最佳答案

    我会用Phaser

    import java.util.concurrent.Phaser;

    class Scratch {
    public static class ThreadABCWorker implements Runnable {
    String threadName;
    Phaser phaser;

    public ThreadABCWorker(String threadName, Phaser phaser) {
    this.threadName = threadName;
    this.phaser = phaser;
    }

    @Override
    public void run() {
    System.out.println("Thread " + threadName + " has started");
    // do steps 1-7 as part of phase 0
    phaser.arriveAndAwaitAdvance();
    // All the work for phase 1 is done in Thread D, so just arrive again and wait for D to do its thing
    phaser.arriveAndAwaitAdvance();
    System.out.println("Continue Thread" + threadName);
    }
    }


    public static void main(String[] args) {
    var phaser = new Phaser(4);
    var threadA = new Thread(new ThreadABCWorker("A", phaser));
    var threadB = new Thread(new ThreadABCWorker("B", phaser));
    var threadC = new Thread(new ThreadABCWorker("C", phaser));
    var threadD = new Thread(() -> {
    phaser.arriveAndAwaitAdvance(); // D shouldn't start doing its thing until phase 1
    System.out.println("Thread D has started");

    try {
    System.out.println("sleep 100");
    Thread.sleep(100);
    System.out.println("Thread D has finished");
    phaser.arriveAndDeregister(); // All done, let ths other threads continue
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    });
    threadA.start();
    threadB.start();
    threadC.start();
    threadD.start();
    }
    }
    输出示例:
    Thread A has started
    Thread C has started
    Thread B has started
    Thread D has started
    sleep 100
    Thread D has finished
    Continue ThreadB
    Continue ThreadA
    Continue ThreadC

    关于java - 并行线程需要到达某个点,等待另一个线程,然后继续执行-最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63696969/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com