/Users/lyon/j4p/src/classUtils/pack/util/tp/test/Test.java

1    package classUtils.pack.util.tp.test; 
2     
3    import java.util.Random; 
4    import classUtils.pack.util.tp.*; 
5     
6    class TestThread { 
7     
8        protected String name; 
9        protected static Random rnd = new Random(); 
10       private static int nextNumber=0; 
11    
12       TestThread(String name) { 
13           if (name==null) name="test-thread"; 
14           this.name=name+"-"+(++nextNumber); 
15       } 
16    
17       TestThread() { 
18           this(null); 
19       } 
20    
21       public String toString() { return name; } 
22   } 
23    
24    
25   class TestThread1 extends TestThread implements Runnable { 
26    
27       TestThread1() { 
28           super("type1"); 
29       } 
30    
31       public void run() { 
32           boolean exit=false; 
33           do { 
34               System.out.println("{"+Thread.currentThread()+"} "+this+" sleeping for 1sec."); 
35               try { 
36                   Thread.sleep(1000); 
37               } catch(InterruptedException e) { 
38                   System.out.println("{"+Thread.currentThread()+"} "+this+" interrupted"); 
39               } 
40               System.out.println("{"+Thread.currentThread()+"} "+this+" awakened"); 
41               int n=rnd.nextInt(3); 
42               switch(n) { 
43                   case 0: 
44                        throw new RuntimeException(this+" failed!"); 
45                   case 1: 
46                       // Continue 
47                       System.out.println("{"+Thread.currentThread()+"} "+this+" continuing processing"); 
48                       break; 
49                   case 2: 
50                       System.out.println("{"+Thread.currentThread()+"} "+this+" exiting"); 
51                       exit=true; 
52                       break; 
53               } 
54           } while(!exit); 
55           System.out.println("{"+Thread.currentThread()+"} "+this+" terminated"); 
56       } 
57   } 
58    
59    
60   /** 
61    * A program to test thread pools 
62    */ 
63   public class Test { 
64    
65       public static void main(String args[]) throws Exception { 
66    
67           ThreadPool tp = new ThreadPool(1, false); 
68           do { 
69               if (tp.getQueueSize() < 5) { 
70                   System.out.println("{"+Thread.currentThread()+"} "+"Creating new test thread"+" ("+tp.getQueueSize()+" in queue)"); 
71                   tp.start(new TestThread1()); 
72               } else System.out.println("{"+Thread.currentThread()+"} "+"Too many threads, waiting for queue to get smaller"); 
73               Thread.sleep(500); 
74           } while(true); 
75       } 
76    
77   }