---
title: "CyclicBarrier类一段小代码的赏析"
author: "atell"
date: "2012-04-03T21:32:46Z"
tags: []
categories: ["编程语言"]
slug: "cyclicbarrier"
draft: false
lastmod: "2012-04-03T21:42:29Z"
id: 1473565
url: "https://atell.iteye.com/blog/1473565"
---

```
              boolean ranAction = false;
               try {
                    final Runnable command = barrierCommand;
                    if (command != null)
                         command.run();
                   ranAction = true;
                   nextGeneration();
                   return 0;
               } finally {
                   if (!ranAction)//通过“try-finally和ranAction布尔标识”，做到这样的效果：如果command.run();抛出异常，则执行 breakBarrier()，但不阻碍异常的如常抛出
                       breakBarrier();
               }
```

 

**这里的技巧是：** 通过“try-finally和ranAction布尔标识”，做到这样的效果：如果command.run();抛出异常，则执行 breakBarrier()，但不阻碍异常的如常抛出。

**如果不这样做，比较一般的做法是：**

try{

     command.run();

     ......

}catch(Throwable e){

     breakBarrier();

     throw e; //或throw new RuntimeException(e.getMessage(), e.getCause() );

}