1. PoolTest(测试类)实现了Runnable接口,在构造函数中创建ThreadPool(线程池类)对象;
执行任务runTask,将线程从Vector freeThreads转移到Vector inUseThreads,并调用PoolableThread的setTask。
2. ThreadPool在构造函数中,创建了10个PoolableThread(控制线程类),start线程,并把线程加入Vector freeThreads里。
3. PoolableThread在开始创建的时候什么也不是做,进入阻塞状态;直到runTask里调用了setTask,notify自己让PoolTest线程 run;
PoolTest run后即刻置null,将线程从Vector inUseThreads转移到Vector freeThreads。
4. PoolTest run的时候打印“线程名开始”,相隔2秒,打印“线程名结束”。
//ThreadPool
package com.wrox.threadpool;
import java.util.*;
public class ThreadPool extends Thread
{
private Vector freeThreads = new Vector();
private Vector inUseThreads = new Vector();
private static int INITIAL_SIZE = 10;
public ThreadPool()
{
fillPool(INITIAL_SIZE);
}
private void fillPool(int poolsize)
{
for(int i=0; i<poolsize; i++)
{
PoolableThread pt = new PoolableThread(this);
pt.start();
freeThreads.add(pt);
}
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
}
}
public synchronized void runTask(Runnable task)
{
if(freeThreads.isEmpty())
{
throw new RuntimeException("ALL threads are in use");
}
PoolableThread t = (PoolableThread)freeThreads.remove(0);
inUseThreads.add(t);
t.setTask(task);
}
synchronized void free(PoolableThread t)
{
inUseThreads.remove(t);
freeThreads.add(t);
}
}
//PoolableThread
package com.wrox.threadpool;
class PoolableThread extends Thread
{
Runnable task = null;
ThreadPool pool;
PoolableThread(ThreadPool pool)
{
this.pool = pool;
}
synchronized void setTask(Runnable task)
{
this.task = task;
notify();
}
synchronized void executeTasks()
{
for(;;)
{
try
{
if(task == null)
{
wait();
}
}
catch(InterruptedException ex)
{
}
task.run();
task = null;
pool.free(this);
}
}
public void run()
{
executeTasks();
}
}
//PoolTest
package com.wrox.threadpool;
public class PoolTest implements Runnable
{
public PoolTest()
{
ThreadPool tp = new ThreadPool();
for(int i=0; i<10; i++)
{
tp.runTask(this);
}
try
{
Thread.sleep(400000);
}
catch(Exception ex)
{
}
}
public static void main(String[] args)
{
PoolTest poolTest1 = new PoolTest();
}
public void run()
{
System.out.println("Start on " + Thread.currentThread().getName());
try
{
Thread.sleep(2000);
}
catch(InterruptedException ex)
{
}
System.out.println("Done on " + Thread.currentThread().getName());
}
}
测试结果:
Start on Thread-3
Start on Thread-1
Start on Thread-8
Start on Thread-5
Start on Thread-10
Start on Thread-2
Start on Thread-7
Start on Thread-9
Start on Thread-4
Start on Thread-6
Done on Thread-3
Done on Thread-8
Done on Thread-1
Done on Thread-5
Done on Thread-7
Done on Thread-2
Done on Thread-10
Done on Thread-6
Done on Thread-4
Done on Thread-9