public void testPharse() {
int size = 100; // 线程个数
final Phaser phaser = new Phaser(size);
ThreadFactory factory = new ThreadFactory() {
int index = 0;
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "线程" + (index++));
}
};
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
ExecutorService executorService = Executors.newFixedThreadPool(size, factory);
for (int i = 0; i < size; i++) {
// System.out.println("进来");
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "等待执行");
try {
int time = new Random().nextInt(5);
TimeUnit.SECONDS.sleep(time);
phaser.arriveAndAwaitAdvance();
time = new Random().nextInt(5);
TimeUnit.SECONDS.sleep(time);
phaser.arriveAndDeregister();
System.out.println(Thread.currentThread().getName() + "执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
});
}
executorService.shutdown();
System.out.println("等待所有线程执行完毕");
while (!phaser.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("所有线程执行完毕");
}