JAVA 多线程同步工具类总结(三)

2014-11-24 10:43:50 · 作者: · 浏览: 2
run() {
long tid = Thread.currentThread().getId();
// 当所有线程完成一轮迭代之后做点清除/准备/提交工作
System.out.printf("[%d] - All threads arrived barrier...%n", tid);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("[%d] - Clear work done...%n", tid);
}

});

// 创建并启动多个线程,他们在 Barrier 上同步
for (int i = 0; i < numOfThread; i++) {
Thread thread = new Thread(new Runnable() {

@Override
public void run() {
long tid = Thread.currentThread().getId();
for ( int k=0; k try {
// 线程进行一轮迭代,做点事情
System.out.printf("Thread %d start its work...%n", tid);
long duration = (int)(Math.random()*5000);
Thread.sleep(duration);
// 做完迭代后等待其他线程完成迭代
System.out.printf("Thread %d wait on barrier...%n", tid);
int num = barrier.await();
// 显示完成的顺序
System.out.printf("Thread %d pass barrier with order=%d...%n", tid, num);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}

});
thread.start();
}

}

}