我手头有以下任务:
想象一下,有 4 名开发人员为 IT 解决方案实施功能,并且有 2 名测试人员来验证他们的工作。项目经理为这个项目制定了一个(有争议的)策略:他不希望测试人员在所有开发人员完成他们的工作之前开始验证这个应用程序。此外,他不希望开发人员在所有测试人员完成工作之前就开始修复报告的缺陷(更改应用程序)。要协调这些任务,请使用 CyclicBarrier 类。
经过一些研究和教程后,我设法编译了以下代码,以便为每个 CycleBarrier 使用 2 个线程:
public static void main(String[] args) {
Runnable barrier1Action = new Runnable() {
public void run() {
System.out.println("Developers start working -> Testers start working");
}
};
Runnable barrier2Action = new Runnable() {
public void run() {
System.out.println("Testers finish working -> Developers start fixing defects");
}
};
CyclicBarrier barrier1 = new CyclicBarrier(2, barrier1Action);
CyclicBarrier barrier2 = new CyclicBarrier(2, barrier2Action);
CyclicBarrierRunnable barrierRunnable1 = new CyclicBarrierRunnable(barrier1, barrier2);
CyclicBarrierRunnable barrierRunnable2 = new CyclicBarrierRunnable(barrier1, barrier2);
new Thread(barrierRunnable1).start();
new Thread(barrierRunnable2).start();
和 CyclicBarrierRunnable 类:
public class CyclicBarrierRunnable implements Runnable {
CyclicBarrier barrier1 = null;
CyclicBarrier barrier2 = null;
public CyclicBarrierRunnable(CyclicBarrier barrier1, CyclicBarrier barrier2) {
this.barrier1 = barrier1;
this.barrier2 = barrier2;
}
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " waiting at barrier 1");
this.barrier1.await();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " waiting at barrier 2");
this.barrier2.await();
System.out.println(Thread.currentThread().getName() + " done!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
我的问题是,如果第一个 CyclicBarrier 有 4 个方而不是 2 个方,我如何使应用程序运行。如果我尝试CyclicBarrier barrier1 = new CyclicBarrier(4, barrier1Action);
CyclicBarrier barrier2 = new CyclicBarrier(2, barrier2Action);
仅使用前 2 个线程来运行它