CountDownLatch and await method exercises

 
Text description: The function of the
 
await method (long timeout, TimeUnit unit) makes the thread enter the WAITING state within the specified maximum time unit. If it exceeds this time, it will automatically wake up and the program continues to run down.

  • timeout is the time to wait
  • unit is the unit of the parameter time

Code above:

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();
        }
    }
}

operation result:
Insert picture description here

Published 475 original articles · Like 16 · Visits 30,000+

Guess you like

Origin blog.csdn.net/qq_32370913/article/details/105579897