CountDownLatch 是 java.util.concurrent包中的一个类.CountDownLatch主要提供的机制是多个线程都达到了预期的状态或完成预期的工作是触发事件.其他线程等待这个事件来触发自己后续的工作。
下面的代码是把一个数组排序任务分配到多个线程,当多个线程排序结束后,再打印结果,当然了,结果是“分段有序的",如果有需要在进行整体的排序。
package learn.day1.synchronizedtest; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestCountDownLatch { public static void main(String[] args) throws IllegalAccessException { int count = 10; final CountDownLatch latch = new CountDownLatch(count); int[] datas = new int[100]; Random random = new Random(); for(int i = 0; i < 100; i++){ int value = random.nextInt(100); datas[i] = value; } for (int data : datas) { System.out.print(data+","); } ThreadPoolExecutor tp = new ThreadPoolExecutor(15,15,60,TimeUnit.SECONDS,new LinkedBlockingQueue<>()); int step = datas.length/count; List<Integer> startIndexs = new ArrayList<>(); for (int i = 0;i < count;i++){ int start = i * step; startIndexs.add(start); int end = (i+1) * step; if( i == count - 1){ end = datas.length; } tp.submit(new MyRunnable(latch,datas,start,end)); } try { latch.await(); for (int data : datas) { System.out.print(data+","); } } catch (InterruptedException e){ } tp.shutdown(); } }
package learn.day1.synchronizedtest; import com.sun.javafx.collections.SortHelper; import learn.day1.sort.SortUtils; import java.util.concurrent.CountDownLatch; public class MyRunnable implements Runnable { private int[] datas; private CountDownLatch latch; private int start; private int end; MyRunnable(CountDownLatch latch,int[] datas,int start,int end) throws IllegalAccessException { if(start > end){ throw new IllegalArgumentException("end must >= start"); } this.datas = datas; this.latch = latch; this.start = start; this.end = end; } @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"正在排序"); SortHelper sortHelper = new SortHelper(); sortHelper.sort(datas,start,end); System.out.println(Thread.currentThread().getName()+"排序结束"); } catch (Exception e) { e.printStackTrace(); }finally { latch.countDown(); } } }