一個簡化的java線程池示例
//以前寫在blogger上的一篇老文了
曾經很好奇線程池是怎么實現的,.net中有現成的線程池可以使用,但是java中沒有。還有就是Servlet的service方法是怎么樣為每一個 Request在不同的線程中獨立服務的,由于Servlet接口沒有繼承自Runnable接口,因此無法直接由一個Servlet對象生成多個線程。后來在網上找到了一個java版本的線程池的例子(http://www.informit.com/articles/article.asp?p= 30483&seqNum=1&rl=1)在該例子的基礎上簡化得到了下面這個版本的java線程池,記錄在這里。
*******************
ThreadPool.java
*******************

package threadPool;

import java.util.ArrayList;
import java.util.Collection;

public class ThreadPool


{
Thread[] threadArray;
Collection<Runnable> jobs = new ArrayList<Runnable>();
public ThreadPool(int threadNum)

{
threadArray = new WorkerThread[threadNum];
for (Thread thread : threadArray)

{
thread = new WorkerThread();
thread.start();
}
}
public synchronized void addJob(Runnable job)

{
jobs.add(job);
notify();
}
private synchronized Runnable getJob()

{
while(jobs.isEmpty())

{
try

{
wait();
} catch (InterruptedException e)

{
e.printStackTrace();
}
}
Runnable job = jobs.iterator().next();
jobs.remove(job);
return job;
}
private class WorkerThread extends Thread

{
public void run()

{
Runnable job = null;
while(job == null)

{
job = getJob();
if(job != null)

{
job.run();
}
job = null;
}
}
}
}


*******************
ThreadPoolTest.java
*******************

package threadPool;

public class ThreadTest


{
private static class PrintClass implements Runnable

{
private int threadNo;
public PrintClass(int threadNo)

{
this.threadNo = threadNo;
}
public void run()

{
for(int i = 0; i < 10; i++)

{
synchronized (System.out)

{
System.out.println("Thread "+threadNo+": "+i);
}
try

{
Thread.sleep(1000);
} catch (InterruptedException e)

{
e.printStackTrace();
}
}
}
}
public static void main(String[] args)

{
ThreadPool tp = new ThreadPool(3);
for(int i=0; i <10; i++)

{
tp.addJob(new PrintClass(i));
}
synchronized (System.out)

{
System.out.println("Job adding finished");
}
}
}
曾經很好奇線程池是怎么實現的,.net中有現成的線程池可以使用,但是java中沒有。還有就是Servlet的service方法是怎么樣為每一個 Request在不同的線程中獨立服務的,由于Servlet接口沒有繼承自Runnable接口,因此無法直接由一個Servlet對象生成多個線程。后來在網上找到了一個java版本的線程池的例子(http://www.informit.com/articles/article.asp?p= 30483&seqNum=1&rl=1)在該例子的基礎上簡化得到了下面這個版本的java線程池,記錄在這里。

































































































































































