CyclicBarrier barrier = new CyclicBarrier(count);//設(shè)置當(dāng)所有的線程都到達(dá)才一起工作
CountDownLatch latch = new CountDownLatch(count);//當(dāng)count減完說明所有的線程都執(zhí)行完畢
完整代碼如下:
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();//線程開始時(shí)要等待所有線程到達(dá)
}
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();//線程結(jié)束時(shí)減去線程數(shù)
}