如何保证线程安全我们都知道,像synchronized,lock等,线程同步使用什么方法呢,这里给大家介绍一个工具CountDownLatch
CountDownLatch可以理解为一个线程同步门闩,它基于AbstractQueueSynchronizer包实现的,具体实现方式大家可以看下源码,这里只对其功能做一个分享
功能主要针对,当一定线程执行完毕后,才执行后面的代码
我们看下面一个例子
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
Thread thread = Thread.currentThread();
@Override
public void run() {
System.out.println("thread:"+thread.currentThread().getName()+" start");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread:"+thread.currentThread().getName()+" end");
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.out.println("mainThread end:"+Thread.currentThread().getState());
}
}
输出为:
thread:Thread-1 start
thread:Thread-3 start
mainThread end:RUNNABLE
thread:Thread-2 start
thread:Thread-0 start
thread:Thread-1 end
thread:Thread-0 end
thread:Thread-3 end
thread:Thread-2 end
我们可以看到上面4个线程没有跑完,最后一句打印 就已经打印出来,那么我们如果想等4个线程执行完以后,后面的代码怎么办呢,就要使用CountDownLatch
请看修改后的代码
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//初始化,入参count为需要等待执行的线程数
CountDownLatch countDownLatch = new CountDownLatch(4);
Runnable runnable = new Runnable() {
Thread thread = Thread.currentThread();
@Override
public void run() {
System.out.println("thread:"+thread.currentThread().getName()+" start");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread:"+thread.currentThread().getName()+" end");
//执行完线程,需要释放countDownLatch中的线程数
countDownLatch.countDown();
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
//执行等待命令
countDownLatch.await();
System.out.println("mainThread end:"+Thread.currentThread().getState());
}
}
打印结果为:
thread:Thread-2 start
thread:Thread-0 start
thread:Thread-3 start
thread:Thread-1 start
thread:Thread-2 end
thread:Thread-1 end
thread:Thread-3 end
thread:Thread-0 end
mainThread end:RUNNABLE