CountDownLatch用法

来源:互联网 发布:wms软件排名 编辑:程序博客网 时间:2024/06/11 16:56
<span style="font-family: Arial, Helvetica, sans-serif;">import java.util.concurrent.CountDownLatch;</span>
/** * Created by lwc on 4/22/16. */public class Test1 {    private int i = 0;    private final CountDownLatch mainLatch = new CountDownLatch(1);    public synchronized void add(){        i++;    }    private class Work extends Thread{        private CountDownLatch threadLatch;        public Work(CountDownLatch latch){            threadLatch = latch;        }        @Override        public void run() {            try {                mainLatch.await();            } catch (InterruptedException e) {                e.printStackTrace();            }            for (int j = 0; j < 1000; j++) {                add();            }            threadLatch.countDown();        }    }    public static void main(String[] args) throws InterruptedException {        for(int k = 0; k < 10; k++){            Test1 test = new Test1();            CountDownLatch threadLatch = new CountDownLatch(10);            for (int i = 0; i < 10; i++) {                test.new Work(threadLatch).start();            }            test.mainLatch.countDown();            threadLatch.await();            System.out.println(test.i);        }    }}

0 0
原创粉丝点击