一、CountDownLatch类
?创建CountDownLatch 对象时,会传入一个count 数值,该对象每次调用countDown() 方法会使count -- ,就是count每次减1; 调用await() 方法,程序会阻塞等待,当count被减到0了之后,await() 后面的程序解除阻塞,可以继续运行。 ?阻塞的是调用await() 方法的后续代码,调用countDown() 方法count自减1,当count=0 时解除阻塞。 ?如:
CountDownLatch countDownLatch = new CountDownLatch(4);
countDownLatch.countDown();
countDownLatch.countDown();
countDownLatch.await();
?代码示例1: 当count不为0时,程序会一直等待。
import java.util.concurrent.CountDownLatch;
public class Test {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"已运行!");
countDownLatch.countDown();
}
}).start();
countDownLatch.await();
System.out.println(" 程序执行完毕! ");
}
}
?代码示例2:count=0解除阻塞。
import java.util.concurrent.CountDownLatch;
public class Test1 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i = 0 ; i < 5 ; i++){
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"已运行!");
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
System.out.println(" 程序执行完毕! ");
}
}
二、CyclicBarrier类
?和CountDownLatch类很类似,创建对象时需要传入一个int数值parties 。某个线程调用await() 方法会阻塞程序,需要parties 个线程调用了await() 方法才会全部解除阻塞。 ?主程序也是一个线程。 ?如:
CyclicBarrier barrier = new CyclicBarrier(3);
barrier.await();
?代码示例:为了能够很明显的体现出效果,创建CyclicBarrier对象,传入4,创建3个线程分别调用await()方法,在await()方法前后分别输出内容。程序睡眠5秒后,主程序调用await()方法。
import lombok.SneakyThrows;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Test1 {
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(4);
for(int i = 0; i < 3 ; i ++){
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始执行");
barrier.await();
System.out.println(Thread.currentThread().getName()+"已执行!");
}
}).start();
}
Thread.sleep(5000);
barrier.await();
System.out.println(" 程序已经执行完! ");
}
}
?程序已运行会输出如下: ?等五秒之后:
|