CountDownLatch与await方法练习

 
文字描述:
 
await方法(long timeout, TimeUnit unit)的作用使线程在指定的最大时间单位内进入WAITING状态,如果超过这个时间则自动唤醒,程序继续向下运行。

  • timeout是等待的时间
  • unit 是参数时间的单位

上代码:

package com.zcw.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @ClassName : MyService
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-17 14:32
 */
public class MyService {
    public CountDownLatch countDownLatch = new CountDownLatch(1);

    public void testMethod(){
        System.out.println(Thread.currentThread().getName()+"准备" +
                System.currentTimeMillis());
        try {
            countDownLatch.await(3, SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"结束"
        +System.currentTimeMillis());
    }
}

package com.zcw.demo;

/**
 * @ClassName : MyThread
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-17 14:37
 */
public class MyThread extends Thread {
    private MyService myService;
    public MyThread(MyService myService){
        super();
        this.myService = myService;
    }
    @Override
    public void run(){
        myService.testMethod();
    }

    public static void main(String[] args) {
        MyService myService = new MyService();
        MyThread[] threads = new MyThread[3];
        for(int i=0;i<threads.length;i++){
            threads[i] = new MyThread(myService);
        }
        for(int i=0;i<threads.length;i++){
            threads[i].start();
        }
    }
}

运行结果:
在这里插入图片描述

发布了475 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32370913/article/details/105579897
今日推荐