CountDownLatch(闭锁)一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个线程或多个线程一直等待(只有等到其他线程全部执行完成,当前运算才执行 )
使用是个线程,打印出10000以内的偶数,并打印花费的时间
1,不适用CountDownLatch情况下
package com.test1;
/**
*
* @author 冷浪进
* @date 2020年4月29日 上午11:57:37
*/
public class TestCountDownLatch {
public static void main(String[] args) {
TestThread tt = new TestThread();
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(tt).start();
}
long end = System.currentTimeMillis();
System.out.println("执行时间:"+(end-start));
}
}
class TestThread implements Runnable {
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 10000; i++) {
if(i%2==0) {
System.out.println(i);
}
}
}
}
}
2,运行结果:并没有打印出消耗时间,因为线程执行没有固定的顺序,所以消耗时间可能提前就打印出来了!
2,使用CountDownLatch(闭锁),使得主线程最后执行完成打印出消耗时间
package com.test1;
import java.util.concurrent.CountDownLatch;
/**
*
* @author 冷浪进
* @date 2020年4月29日 上午11:57:37
*/
public class TestCountDownLatch {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(10);
TestThread tt = new TestThread(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(tt).start();
}
try {
latch.await();//保证下面的最后执行
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("执行时间:"+(end-start));
}
}
class TestThread implements Runnable {
private CountDownLatch latch;
public TestThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 10000; i++) {
if(i%2==0) {
System.out.println(i);
}
}
} finally {
latch.countDown();
}
}
}
}
2,运行结果:打印出了执行时间