欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK5 concurrent 并行包之CyclicBarrier

程序员文章站 2022-04-17 18:45:57
...
package projects.debug.learn;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class part1
{

/**
* This static mehthod create CyclicBarrier, and this barrier will sleep 1000 if number of count arrive
* @param number of count
* @return a CyclicBarrier that will sleep if number of await thread invoke.
*/

public static CyclicBarrier getCyclicBarrier(int count)
{
if (count <= 0)
return null;
final CyclicBarrier cyclicBarrier = new CyclicBarrier(count,
new Runnable()
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out
.println("conditon is arrive and CycleBarrier is running");
}
});
return cyclicBarrier;
}

/**
* Create
* @param nameOfThread
* @param cyclicBarrier
* @return
*/
public static Thread getThread(String nameOfThread,
final CyclicBarrier cyclicBarrier)
{
Thread thread = new Thread(nameOfThread)
{
public void run()
{
System.out.println(this.getName() + "is begin; and count is "
+ (++count));
try
{
cyclicBarrier.await();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (BrokenBarrierException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName() + "finished");
}
};
return thread;

}

static int count = 0;

public static void main(String[] args)
{
CyclicBarrier cyclicBarrier = getCyclicBarrier(2);
Thread threadOne = getThread("threadOne", cyclicBarrier);
threadOne.start();
Thread threadTwo = getThread("threadTwo", cyclicBarrier);
threadTwo.start();

}

}
相关标签: thread