gpt4 book ai didi

Java 线程 : How to execute a statement simultaneously

转载 作者:行者123 更新时间:2023-11-29 08:36:41 28 4
gpt4 key购买 nike

考虑我有一个如下所示的运行方法,我正在尝试为 MyThread 创建四个线程。语句 1 到 3 可以由线程同时运行,也可以不同地运行。但是我想让Statement 4同时被线程执行。我可以在语句 4 之前合并所有线程并由所有线程同时执行语句 4 吗?

class MyThread extends Thread
{
public void run()
{
//Statement 1
//Statement 2
//Statement 3
//Statement 4
}

}

最佳答案

使用 CyclicBarrier,它最适合您的要求。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierUsage {

private static final int NUMBER_OF_THREADS = 2;

public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_THREADS);

Thread t1 = new Thread(new PrimaryParty(barrier));
Thread t2 = new Thread(new PrimaryParty(barrier));

t1.start();
t2.start();
}
}

class PrimaryParty implements Runnable {

private CyclicBarrier barrier;

public PrimaryParty(CyclicBarrier barrier) {
this.barrier = barrier;
}

@Override
public void run() {
//Statement 1
//Statement 2
//Statement 3

try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}

//Statement 4
}
}

关于Java 线程 : How to execute a statement simultaneously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547991/

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