CyclicBarrier barrier = new CyclicBarrier(count);//设置当所有的线程都到达才一起工作
CountDownLatch latch = new CountDownLatch(count);//当count减完说明所有的线程都执行完毕
完整代码如下:
public static void main(String[] args) throws InterruptedException
{
int count = 20;
CyclicBarrier barrier = new CyclicBarrier(count);
CountDownLatch latch = new CountDownLatch(count);
long t0 = System.currentTimeMillis();
for (int i = 0; i < count; i++)
{
new Thread(new tenThree(barrier, latch)).start();
}
latch.await();//等待所有线程完毕
long t1 = System.currentTimeMillis();
System.out.println(t1 - t0);
}
tenThree的run方法:
public void run()
{
// TODO Auto-generated method stub
LogEvent logEvent = new WriteDisk();
try
{
barrier.await();//线程开始时要等待所有线程到达
}
catch (InterruptedException | BrokenBarrierException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.limit(512);
for (int i = 0; i < 10; i++)
{
logEvent.write(buffer);
buffer.position(0);
}
latch.countDown();//线程结束时减去线程数
}
网友评论