【Java/CountDownLatch】使用CountDownLatch实现睡眠排序
刚才在 https://news.cnblogs.com/n/703437/ 上看到有人提到有趣的“睡眠排序”,忽然想到CountDownLatch正好可以用于实现一个。代码如下:
package ufo.sleepsort; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; class SleepThread extends Thread{ private int seconds; private List<Integer> ls; private CountDownLatch latch; public SleepThread(int seconds,List<Integer> ls,CountDownLatch latch) { this.seconds=seconds; this.ls=ls; this.latch=latch; } public void run() { try { Thread.sleep(seconds*1000); ls.add(seconds); latch.countDown(); }catch(Exception ex) { ex.printStackTrace(); } } } public class SleepSortor { public static void main(String[] args) throws Exception{ int[] arr= {2,4,6,13,1,5,7}; final CountDownLatch latch=new CountDownLatch(arr.length); List<Integer> ls=new ArrayList<>(); for(int it:arr) { SleepThread st=new SleepThread(it,ls,latch); st.start(); } latch.await(); //排序结束 for(int i:ls) { System.out.println(i); } } }
输出:
1 2 4 5 6 7 13
正如预期。
有兴趣的朋友可以参照着试一试。
END