多线程中CountDownLatch的使用

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

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

new Thread(new Runnable() {线程

@Overrideit

public void run() {io

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

try {im

Thread.sleep(10);static

} catch (InterruptedException e) {img

}di

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


二、使用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

相关文章
相关标签/搜索