多线程-使用CyclicBarrier达到join的效果

阅读更多
//多线程-使用CyclicBarrier达到join的效果
public class JoinTest {

public static void main(String[] args) {
int threadNum = 20;
CyclicBarrier barrier=new CyclicBarrier(threadNum, new PrintThread());
for(int i=0;i new Thread(new Task(barrier)).start();
}
}
    //Task线程执行完之后,再执行PrintThread
static class PrintThread implements Runnable{
public void run(){
System.out.println("game over!");
}
}

static class Task implements Runnable{
private CyclicBarrier barrier;

public Task(CyclicBarrier barrier){
this.barrier = barrier;
}

public void run(){
System.out.println("game is running..");

//阻塞,直到所有的Task线程都执行完
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}

你可能感兴趣的:(多线程)