多线程中CountDownLatch的使用

1、原始代如下,如何保证线程一、线程二执行完之后,再执行System.out.println("主线程")

public static void main(String[] args) throws Exception{

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("子线程1开始执行");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

}

System.out.println("子线程1执行结束");

}

}).start();

 

 

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("子线程2开始执行");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

}

System.out.println("子线程2执行结束");

}

}).start();

 

System.out.println("主线程");

  }


执行结果如下

image.png


2、使用CountDownLatch

public static void main(String[] args) throws Exception{

CountDownLatch count = new CountDownLatch(2);

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("子线程1开始执行");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

}

System.out.println("子线程1执行结束");

count.countDown();

}

}).start();

 

 

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("子线程2开始执行");

try {

Thread.sleep(10);

} catch (InterruptedException e) {

}

System.out.println("子线程2执行结束");

count.countDown();

}

}).start();

count.await();

System.out.println("主线程");

  }



执行结果如下

image.png


猜你喜欢

转载自blog.51cto.com/4923168/2299152