Advertisement
Guest User

SleepSort

a guest
Jul 22nd, 2011
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.concurrent.CountDownLatch;
  3.  
  4.  
  5. public class SleepSort {
  6.    
  7.     private static volatile ArrayList<Integer> sorted = new ArrayList<Integer>();
  8.     /**
  9.      * @param args
  10.      */
  11.     public static void main(String[] args) {
  12.         CountDownLatch latch = new CountDownLatch(args.length);
  13.         for(String string : args){
  14.             Integer num = Integer.parseInt(string);
  15.             new AddToListRunnable(num, latch).start();
  16.         }
  17.         try {
  18.             latch.await();
  19.             System.out.println(sorted);
  20.         }
  21.         catch (InterruptedException e) {
  22.             e.printStackTrace();
  23.         }
  24.     }
  25.    
  26.    
  27.     private static class AddToListRunnable extends Thread {
  28.  
  29.         private final Integer number;
  30.         private final CountDownLatch latch;
  31.         public AddToListRunnable(Integer number, CountDownLatch latch){
  32.             this.number = number;
  33.             this.latch = latch;
  34.         }
  35.        
  36.         @Override
  37.         public void run() {
  38.             try {
  39.                 sleep(number * 1000l);
  40.                 sorted.add(number);
  41.                 latch.countDown();
  42.                 System.out.println(latch.getCount());
  43.             }
  44.             catch (InterruptedException e) {
  45.                 e.printStackTrace();
  46.             }
  47.         }
  48.        
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement