CountDownLatch和CyclicBarrier分别都是在什么时候使用的?

下面是我写的代码,作用是开启n个线程,执行插入语句

然后...没发现有什么区别....

 public class Task implements Runnable {

    int id;
    CyclicBarrier barrier;

    public Task(int _id, CyclicBarrier _barrier) {
        id = _id;
        barrier = _barrier;
    }

    @Override
    public void run() {
        System.out.println(id + " begin");
        Dao dao = new Dao();
        int n = 1000;
        for (int i = 0; i < n; i++) {
            dao.add("insert into test(id, name) values(?, ?)", 1, 1);
        }
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(id + " end");

    }
}
 public class Task implements Runnable {

    int id;
    CountDownLatch latch;

    public Task(int _id, CountDownLatch _latch) {
        id = _id;
        latch = _latch;
    }

    @Override
    public void run() {
        System.out.println(id + "-begin");
        addOracle();
        latch.countDown();
        System.out.println(id + "-end");

    }

    public void addOracle() {
        Dao dao = new Dao();
        int n = 100;
        for (int i = 0; i < n; i++) {
            dao.add("insert into test(id, name) values(?, ?)", i, i);
        }
    }
}

0

1个回答

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!