java 多线程通知 CountDownLatch 倒数计数器的使用

package com.hra.riskprice;

import com.hra.riskprice.SysEnum.Factor_Type;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

class R1 implements   Runnable{
   public static int i=1;
    @Override
    public void run() {

        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = new Date();
            String dateNowStr = sdf.format(d);
            System.out.println("before:");
            System.out.println(dateNowStr);
            System.out.println("当前值是:"+i++);
            Thread.sleep(3000);
            System.out.println("after:");
            System.out.println(dateNowStr);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
@SpringBootApplication
public class RiskpriceApplication {


     public static  long time (int concurrency, final  Runnable action)throws InterruptedException{
         final CountDownLatch ready=new CountDownLatch(concurrency);
         final  CountDownLatch start=new CountDownLatch(1);
         final CountDownLatch  done=new CountDownLatch(concurrency);
         for(int i=0;i<5;i++){
                new Thread(new Runnable() {
                     @Override
                     public void run() {
                         ready.countDown();
                         try {
                             start.await();
                             action.run();
                         } catch (InterruptedException e) {
                             Thread.currentThread().interrupt();
                         }catch (Exception ex){
                             String msg=ex.getMessage();
                         }
                         finally {
                             done.countDown();
                         }
                     }
                 }).start();



         }
         ready.await();
         long startNano=System.nanoTime();
         start.countDown();
         done.await();
         return System.nanoTime()-startNano;

     }

    public static void main(String[] args)    {
         R1 r=new R1();

        try{
          long l=time(5,r)/1000;
          System.out.println("用时:"+l);
        }
        catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }
    }
}


注意   for(int i=0;i<concurrency;i++)代码concurrency的当前值是5,这个数值如果小于5,就会造成线程饥饿死锁 ,也就是说至少要创建与指定并发级别一样多的线程,否则这个测试永远不会结束

猜你喜欢

转载自www.cnblogs.com/kexb/p/10164617.html