新的起点 新的开始

快乐生活 !

学习实践 JDK5 concurrent 并行包之CyclicBarrier

本部分介绍CyclicBarrier类,该类通ReentrantLock 跟Condition。Barrier 顾名思义,只有所有线程数达到规定的数量时,它才会被触发执行。
如下段代码 只有线程12都执行时,才会执行它定义的线程。

1 package net.vincent.study.other;
 2 
 3 import java.util.concurrent.BrokenBarrierException;
 4 import java.util.concurrent.CyclicBarrier;
 5 
 6 public class part1 {
 7 
 8     /**
 9      * This static mehthod create CyclicBarrier, and this barrier will sleep 1000 if number of count arrive 
10      * @param number of count 
11      * @return a CyclicBarrier that will sleep if number of await thread invoke. 
12      */
13 
14     public static CyclicBarrier getCyclicBarrier(int count){
15         if(count <=0)return null;
16          final CyclicBarrier cyclicBarrier = new CyclicBarrier(count,new Runnable(){
17             public void run(){
18                 try {
19                     Thread.sleep(1000);
20                 } catch (InterruptedException e) {
21                     e.printStackTrace();
22                 }
23                 System.out.println("conditon is arrive and CycleBarrier is running");
24             }
25         });
26         return cyclicBarrier;
27     }
28     /**
29      * Create
30      * @param nameOfThread
31      * @param cyclicBarrier
32      * @return
33      */
34     public static Thread getThread(String nameOfThread ,final CyclicBarrier  cyclicBarrier ){
35         Thread thread= new Thread(nameOfThread){
36         public void run(){
37                 System.out.println(this.getName()+"is begin; and count is "+(++count));
38             try {
39                 cyclicBarrier.await();
40             } catch (InterruptedException e) {
41                 // TODO Auto-generated catch block
42                 e.printStackTrace();
43             } catch (BrokenBarrierException e) {
44                 // TODO Auto-generated catch block
45                 e.printStackTrace();
46             }
47             System.out.println(this.getName()+"finished");
48             }
49         };
50         return thread;
51         
52     }
53     
54     static  int count = 0;
55     public static void main(String[] args) {
56         /** define a cyclicBarrier and number of barrier is 2.*/
57         CyclicBarrier cyclicBarrier  = getCyclicBarrier(2);
58         Thread threadOne = getThread("threadOne",cyclicBarrier);
59         threadOne.start();
60         Thread threadTwo = getThread("threadTwo",cyclicBarrier);
61         threadTwo.start();
62 
63 
64     }
65 
66 
67 }
68 

posted on 2007-09-28 14:51 advincenting 阅读(1454) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

公告

Locations of visitors to this page

导航

<2007年9月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

统计

常用链接

留言簿(13)

随笔分类(71)

随笔档案(179)

文章档案(13)

新闻分类

IT人的英语学习网站

JAVA站点

优秀个人博客链接

官网学习站点

生活工作站点

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜