CyclicBarrier 的應用

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;

public class Client {


    public void meeting(CyclicBarrier barrier){
        try {
            Thread.sleep(ThreadLocalRandom.current().nextInt(3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() +" 在等待開會");
        try {
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread()+" 發言");
    }


    public static void main(String[] args) {
        int num=10;
        CyclicBarrier barrier=new CyclicBarrier(num, new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread()+" 能夠開會了...");
            }
        });
        Client client=new Client();
        for (int i = 0; i < num; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    client.meeting(barrier);
                }
            }).start();
        }

    } 
}
相關文章
相關標籤/搜索