countdownlatch和semaphore

CountDownLatch:

CountDownLatch允许一个或多个线程等待其他线程完成操作;

CountDownLatch需要指定一个整数值,此值是线程将要等待的操作数,当减为0时,才会唤醒所有await的线程,一个countdownlatch只能用一次

public class CountDown1 {
static CountDownLatch c=new CountDownLatch(3);

public static void main(String[] args) throws InterruptedException {
new Thread(()->{
try{
System.out.println("我在干活");
c.countDown();//干完就减1
}catch (Exception e){
e.printStackTrace();
}
}).start();


new Thread(()->{
try{
System.out.println("我在干活1");
c.countDown();//干完就减1
}catch (Exception e){
e.printStackTrace();
}
}).start();
new Thread(()->{
try{
System.out.println("我在干活2");
c.countDown();//干完就减1
}catch (Exception e){
e.printStackTrace();
}
}).start();
c.await();//当C减为0时,才执行此条之后的代码 countdown的缺点是只能用一次,减为0之后就不能用了
System.out.println("结束");
}
}
//Semaphore控制只有多少线程同时访问一个资源,可以用来做限流
public class Semaphore01 {
    static Semaphore semaphore = new Semaphore(5);
public static void main(String[] args) {
for(int i=0;i<20;i++){
final int j=i;
new Thread(()->{
try{
action(j);
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
public static void action(int j) throws InterruptedException {
//每次只允许5个线程同时执行下面的代码块
semaphore.acquire();
System.out.println(j+"在京东秒杀");
try{
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(j+"秒杀成功");
semaphore.release();
}
}
posted @ 2020-06-11 22:40  zpp13  阅读(311)  评论(0编辑  收藏  举报