多线程CountDownLatch

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class a200604多线程CountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(7);//设置为7,减成0时await()的线程开始。


        Customer cs = new Customer("顾客",latch);

        for(int i = 0 ; i <3;i++){
            new Thread(cs).start();
        }
        new Thread(new Waitress("服务员",latch)).start();

        Thread.sleep(6000);
         new Thread(cs).start();

    }
}


//顾客类
class Customer implements Runnable{
    private String name;
    private CountDownLatch latch;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Customer(String name, CountDownLatch latch) {
        this.name = name;
        this.latch = latch;
    }

    @Override
    public void run() {
        latch.countDown();//计数器-1
        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM--dd hh:MM:ss:SSS");
        Date date = new Date();
        String str = sp.format(date);
        System.out.println(str+"    "+name+"来到了店里");
    }
}

//服务员类
class Waitress implements Runnable{
    private  String name;
    private CountDownLatch latch;

    public Waitress(String name, CountDownLatch latch) {
        this.name = name;
        this.latch = latch;
    }


    public void run() {
        try{

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM--dd  hh:MM:ss:SSS");
            System.out.println(dateFormat.format(new Date())+"    "+ name+"等候顾客");
            latch.await(5,TimeUnit.SECONDS);
            System.out.println(dateFormat.format(new Date())+"    " +name+"开始服务");
        }catch (Exception e){
            e.printStackTrace();

        }
    }
}

countdownLatch中有await(),有countdown()。实例化countdownLatch()时也会实例化一个继承了AbstractQueuedSynchronizer的Sync的内部类的对象,cutdown()会调用Sync的方法。cutdown()每被调用一次,就会将计数器减一。计数器大于0时,调用了await()的线程将一直被阻塞,等于0时被释放。await()也可设定时间调用其另一重载,在该时间到达时释放线程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值