今天有一个需求是:在一个方法中开启了一个子线程来执行操作,返回值依赖于子线程的执行结果,这样如果要返回正确的值,就需要开启子线程后
主线程等待子线程,然后子线程执行结束后,主线程再继续执行。
主线程等待子线程需要用到:CountDownLatch
代码如下:
- import java.util.concurrent.CountDownLatch;
-
-
- public class Counter {
- public static int count = 0;
- static CountDownLatch cdl=new CountDownLatch(1000);
-
- public synchronized static void inc() throws InterruptedException{
- Thread.sleep(1);
- count++;
- cdl.countDown();
- }
-
- public static void main(String[] args) throws InterruptedException{
-
- for(int i = 0; i < 1000; i++){
- new Thread(new Runnable(){
-
- public void run() {
-
- try {
- Counter.inc();
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- }
-
- }
- ).start();
- }
- cdl.await();
- System.out.println(count);
- }
- }