用java演示栅栏模式
时间: 2023-07-18 09:35:50 浏览: 51
栅栏模式是一种同步模式,它可以让一组线程在特定的时刻点上相互等待,直到所有线程都到达这个点之后才能继续执行。在Java中,可以使用CyclicBarrier类来实现栅栏模式。
下面是一个简单的Java程序,演示了如何使用CyclicBarrier类实现栅栏模式:
```java
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class BarrierDemo {
public static void main(String[] args) {
int parties = 3; // 栅栏需要等待的线程数
CyclicBarrier barrier = new CyclicBarrier(parties, new Runnable() {
// 所有线程都到达栅栏时执行的动作
@Override
public void run() {
System.out.println("All parties have arrived at the barrier");
}
});
Thread t1 = new Thread(new Worker(barrier), "Thread 1");
Thread t2 = new Thread(new Worker(barrier), "Thread 2");
Thread t3 = new Thread(new Worker(barrier), "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
class Worker implements Runnable {
private final CyclicBarrier barrier;
public Worker(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting at the barrier");
barrier.await(); // 等待所有线程到达栅栏
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
```
在这个程序中,有三个线程(t1、t2和t3)需要等待在栅栏处。当所有线程都到达栅栏处时,会执行Runnable对象中定义的动作。然后所有线程会继续执行它们的任务。
输出结果如下:
```
Thread 1 is waiting at the barrier
Thread 3 is waiting at the barrier
Thread 2 is waiting at the barrier
All parties have arrived at the barrier
Thread 3 has crossed the barrier
Thread 2 has crossed the barrier
Thread 1 has crossed the barrier
```
可以看到,所有线程都需要等待在栅栏处,直到所有线程都到达栅栏处之后才能继续执行。