由于此测试程序用到了输入输入类,因此第1行导入了JAVA的基本IO处理包,在第11行中,我们创建了一个名为manager的类,它给ThreadPoolManager类的构造函数传递了一个值为10的参数,告诉ThreadPoolManager类:我要一个有10个线程的池,给我创建一个吧!第12行至15行是一个无限循环,它用来等待用户的键入,并将键入的字符串保存在s变量中,并调用ThreadPoolManager类的process方法来将这个请求进行处理。
下面我们再进一步跟踪到ThreadPoolManager类中去,以下是它的源代码:
//ThreadPoolManager.java
1 import java.util.*;
2
3
4 class ThreadPoolManager
5 {
6
7 private int maxThread;
8 public Vector vector;
9 public void setMaxThread(int threadCount)
10 {
11 maxThread = threadCount;
12 }
13
14 public ThreadPoolManager(int threadCount)
15 {
16 setMaxThread(threadCount);
17 System.out.println("Starting thread pool...");
18 vector = new Vector();
19 for(int i = 1; i <= 10; i++)
20 {
21 SimpleThread thread = new SimpleThread(i);
22 vector.addElement(thread);
23 thread.start();
24 }
25 }
26
27 public void process(String argument)
28 {
29 int i;
30 for(i = 0; i < vector.size(); i++)
31 {
32 SimpleThread currentThread = (SimpleThread)vector.elementAt(i);
33 if(!currentThread.isRunning())
34 {
35 System.out.println("Thread "+ (i+1) +" is processing:" +
argument);
36 currentThread.setArgument(argument);
37 currentThread.setRunning(true);
38 return;
39 }
40 }
41 if(i == vector.size())
42 {
43 System.out.println("pool is full, try in another time.");
44 }
45 }
46 }//end of class ThreadPoolManager
查看本文来源