一、浩句
看看星空,会觉得自己很渺小,可能我们在宇宙中从来就是一个偶然。所以,无论什么事情,仔细想一想,都没有什么大不了的。这能帮助自己在遇到挫折时稳定心态,想得更开
二、背景
CountDownLatch 用于控制线程时序性,个人理解线程时序性即是线程的执行顺序。
三、code
CountDownLatch 使用,可以控制线程,等待其他线程执行完在继续往下执行,这是其中的一种实现方式之一
package com.mouse.moon.countDownLatch;
import java.util.concurrent.CountDownLatch;
public class Cat implements Runnable{
private final CountDownLatch count ;
public Cat(int num){
count = new CountDownLatch(num);
}
public void eat(String name){
System.out.println("吃了。。。。"+name);
count.countDown();
System.out.println("还有剩余的数量------->"+count.getCount());
}
@Override
public void run() {
System.out.println("count的开始大小="+count.getCount());
try {
count.await();
System.out.println("到cat吃饭了,只剩渣了!!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.mouse.moon.countDownLatch;
import java.util.concurrent.TimeUnit;
public class Dog implements Runnable {
private Cat cat;
private String foodName;
public Dog(Cat cat,String foodName){
this.cat = cat;
this.foodName = foodName;
}
@Override
public void run() {
long duration = (long)(Math.random()*10);
try {
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
cat.eat(foodName);
}
}
package com.mouse.moon.countDownLatch;
public class AppMain {
public static void main(String args[]){
Cat cat =new Cat(5);
Thread thread = new Thread(cat);
thread.start();
for(int i=0;i < 5;i++){
Dog dog =new Dog(cat,"food--"+i);
Thread dogThread = new Thread(dog);
dogThread.start();
}
}
}
count.await();调用后,将等待其他全部执行完。初始化的时候初始化大小,然后在每次执行完后count.countDown()就会减1;直到为0,则将唤醒素有count.await()等待线程将继续执行。