1. 程式人生 > >java 多執行緒通知 CountDownLatch 倒數計數器的使用

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,就會造成執行緒飢餓死鎖 ,也就是說至少要建立與指定併發級別一樣多的執行緒,否則這個測試永遠不會結束