1 16 17 package org.apache.batik.util; 18 19 import java.util.ArrayList ; 20 import java.util.List ; 21 import java.util.Iterator ; 22 import java.util.Collections ; 23 import java.util.Random ; 24 25 32 public class ThreadPounder { 33 List runnables; 34 Object [] threads; 35 Object lock = new Object (); 36 37 public ThreadPounder(List runnables) 38 throws InterruptedException { 39 this(runnables, new Random (1234)); 40 } 41 42 public ThreadPounder(List runnables, Random rand) 43 throws InterruptedException { 44 this.runnables = new ArrayList (runnables); 45 Collections.shuffle(this.runnables, rand); 46 threads = new Object [this.runnables.size()]; 47 int i=0; 48 Iterator iter= this.runnables.iterator(); 49 synchronized (lock) { 50 while (iter.hasNext()) { 51 Thread t = new SyncThread((Runnable )iter.next()); 52 t.start(); 53 lock.wait(); 54 threads[i] = t; 55 i++; 56 } 57 } 58 } 59 60 public void start() { 61 synchronized(this) { 62 this.notifyAll(); 63 } 64 65 } 66 67 class SyncThread extends Thread { 68 Runnable toRun; 69 public long runTime; 70 public SyncThread(Runnable toRun) { 71 this.toRun = toRun; 72 } 73 74 public void run() { 75 try { 76 synchronized (ThreadPounder.this) { 77 synchronized (lock) { 78 lock.notify(); 80 } 81 ThreadPounder.this.wait(); 83 } 84 toRun.run(); 85 } catch (InterruptedException ie) { 86 } 87 } 88 } 89 90 public static void main(String [] str) { 91 List l = new ArrayList (20); 92 for (int i=0; i<20; i++) { 93 final int x = i; 94 l.add(new Runnable () { 95 public void run() { 96 System.out.println("Thread " + x); 97 } 98 }); 99 } 100 101 try { 102 ThreadPounder tp = new ThreadPounder(l); 103 System.out.println("Starting:" ); 104 tp.start(); 105 System.out.println("All Started:" ); 106 } catch (InterruptedException ie) { 107 ie.printStackTrace(); 108 } 109 } 110 } 111 | Popular Tags |