---
# System prepended metadata

title: CyclicBarrier的用法
tags: [ocpjp]

---

# CyclicBarrier的用法
```java=
class Worker extends Thread {
 
    CyclicBarrier cb;
 
    public Worker(CyclicBarrier cb) {
        this.cb = cb;
    }
 
    public void run() {
        try {
            cb.await();
            System.out.println("Worker...");
        } catch (Exception ex) {
        }
    }
}
 
class Master implements Runnable { //line n1
 
    public void run() {
        System.out.println("Master...");
    }
}
```
and the code fragment:
```java=
Master master = new Master();
//line n2
Worker worker = new Worker(cb);
worker.start();
```
You have been asked to ensure that the run methods of both the Worker and Master classes are executed.

### Which modification meets the requirement?
A. At line n2, insert CyclicBarrier cb = new CyclicBarrier(2, master);
B. Replace line n1 with class Master extends Thread {
**C. At line n2, insert CyclicBarrier cb = new CyclicBarrier(1, master);**
D. At line n2, insert CyclicBarrier cb = new CyclicBarrier(master);
- [x] **Answer:C**

- [參考網站](https://magiclen.org/ocpjp-cyclicbarrier/)
- [CyclicBarrier的 用法簡單範例](https://my.oschina.net/u/3680947/blog/3025985)

:::info
CyclicBarrier是Java內建的類別，位於java.util.concurrent套件下，**用來讓某個執行緒等待至指定數量的執行緒呼叫CyclicBarrier的await方法後才繼續執行**

---
**CyclicBarrier cb = new CyclicBarrier(count, runnable);**

---
- 選項A，此種CyclicBarrier物件實體化方式需要呼叫兩次CyclicBarrier的await方法後，await方法之後的程式才會被執行，但是在題目給的程式中，await只有在第11行被呼叫過，因此永遠執行不到第12行，而且也無法執行master這個Runnable物件。

- 選項B，應該要修改line n2才是正確的。

- 選項C，此種CyclicBarrier物件實體化方式只需要呼叫一次CyclicBarrier的await方法後，傳入CyclicBarrier建構子的master這個Runnable物件和await方法之後的程式都會被執行，所以這是正確答案。

- 選項D，CyclicBarrier類別沒有這種建構子。
:::

###### tags: `ocpjp`