线程池的做用: java
线程池做用就是限制系统中执行线程的数量。
根据系统的环境状况,能够自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了形成系统拥挤效率不高。用线程池控制线程数量,其余线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务须要运行时,若是线程池中有等待的工做线程,就能够开始运行了;不然进入等待队列。 服务器
为何要用线程池: 测试
- 减小了建立和销毁线程的次数,每一个工做线程均可以被重复利用,可执行多个任务
- 能够根据系统的承受能力,调整线程池中工做线线程的数目,防止由于由于消耗过多的内存,而把服务器累趴下(每一个线程须要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)
线程池类 this
- package com.tdt.impl.ls;
-
- import java.util.LinkedList;
-
- /**
- * @project LocationGateway
- * @author sunnylocus
- * @verson 1.0.0
- * @date Aug 2, 2008
- * @jdk 1.4.2
- */
- public class ThreadPool extends ThreadGroup {
- private boolean isClosed = false; //线程池是否关闭
- private LinkedList workQueue; //工做队列
- private static int threadPoolID = 1; //线程池的id
- public ThreadPool(int poolSize) { //poolSize 表示线程池中的工做线程的数量
-
- super(threadPoolID + ""); //指定ThreadGroup的名称
- setDaemon(true); //继承到的方法,设置是否守护线程池
- workQueue = new LinkedList(); //建立工做队列
- for(int i = 0; i < poolSize; i++) {
- new WorkThread(i).start(); //建立并启动工做线程,线程池数量是多少就建立多少个工做线程
- }
- }
-
- /** 向工做队列中加入一个新任务,由工做线程去执行该任务*/
- public synchronized void execute(Runnable task) {
- if(isClosed) {
- throw new IllegalStateException();
- }
- if(task != null) {
- workQueue.add(task);//向队列中加入一个任务
- notify(); //唤醒一个正在getTask()方法中待任务的工做线程
- }
- }
-
- /** 从工做队列中取出一个任务,工做线程会调用此方法*/
- private synchronized Runnable getTask(int threadid) throws InterruptedException {
- while(workQueue.size() == 0) {
- if(isClosed) return null;
- System.out.println("工做线程"+threadid+"等待任务...");
- wait(); //若是工做队列中没有任务,就等待任务
- }
- System.out.println("工做线程"+threadid+"开始执行任务...");
- return (Runnable) workQueue.removeFirst(); //反回队列中第一个元素,并从队列中删除
- }
-
- /** 关闭线程池 */
- public synchronized void closePool() {
- if(! isClosed) {
- waitFinish(); //等待工做线程执行完毕
- isClosed = true;
- workQueue.clear(); //清空工做队列
- interrupt(); //中断线程池中的全部的工做线程,此方法继承自ThreadGroup类
- }
- }
-
- /** 等待工做线程把全部任务执行完毕*/
- public void waitFinish() {
- synchronized (this) {
- isClosed = true;
- notifyAll(); //唤醒全部还在getTask()方法中等待任务的工做线程
- }
- Thread[] threads = new Thread[activeCount()]; //activeCount() 返回该线程组中活动线程的估计值。
- int count = enumerate(threads); //enumerate()方法继承自ThreadGroup类,根据活动线程的估计值得到线程组中当前全部活动的工做线程
- for(int i =0; i < count; i++) { //等待全部工做线程结束
- try {
- threads[i].join(); //等待工做线程结束
- }catch(InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- }
-
- /**
- * 内部类,工做线程,负责从工做队列中取出任务,并执行
- * @author sunnylocus
- */
- private class WorkThread extends Thread {
- private int id;
- public WorkThread(int id) {
- //父类构造方法,将线程加入到当前ThreadPool线程组中
- super(ThreadPool.this,id+"");
- this.id =id;
- }
- public void run() {
- while(! isInterrupted()) { //isInterrupted()方法继承自Thread类,判断线程是否被中断
- Runnable task = null;
- try {
- task = getTask(id); //取出任务
- }catch(InterruptedException ex) {
- ex.printStackTrace();
- }
- //若是getTask()返回null或者线程执行getTask()时被中断,则结束此线程
- if(task == null) return;
-
- try {
- task.run(); //运行任务
- }catch(Throwable t) {
- t.printStackTrace();
- }
- }// end while
- }// end run
- }// end workThread
- }
package com.tdt.impl.ls;
import java.util.LinkedList;
/**
* @project LocationGateway
* @author sunnylocus
* @verson 1.0.0
* @date Aug 2, 2008
* @jdk 1.4.2
*/
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false; //线程池是否关闭
private LinkedList workQueue; //工做队列
private static int threadPoolID = 1; //线程池的id
public ThreadPool(int poolSize) { //poolSize 表示线程池中的工做线程的数量
super(threadPoolID + ""); //指定ThreadGroup的名称
setDaemon(true); //继承到的方法,设置是否守护线程池
workQueue = new LinkedList(); //建立工做队列
for(int i = 0; i < poolSize; i++) {
new WorkThread(i).start(); //建立并启动工做线程,线程池数量是多少就建立多少个工做线程
}
}
/** 向工做队列中加入一个新任务,由工做线程去执行该任务*/
public synchronized void execute(Runnable task) {
if(isClosed) {
throw new IllegalStateException();
}
if(task != null) {
workQueue.add(task);//向队列中加入一个任务
notify(); //唤醒一个正在getTask()方法中待任务的工做线程
}
}
/** 从工做队列中取出一个任务,工做线程会调用此方法*/
private synchronized Runnable getTask(int threadid) throws InterruptedException {
while(workQueue.size() == 0) {
if(isClosed) return null;
System.out.println("工做线程"+threadid+"等待任务...");
wait(); //若是工做队列中没有任务,就等待任务
}
System.out.println("工做线程"+threadid+"开始执行任务...");
return (Runnable) workQueue.removeFirst(); //反回队列中第一个元素,并从队列中删除
}
/** 关闭线程池 */
public synchronized void closePool() {
if(! isClosed) {
waitFinish(); //等待工做线程执行完毕
isClosed = true;
workQueue.clear(); //清空工做队列
interrupt(); //中断线程池中的全部的工做线程,此方法继承自ThreadGroup类
}
}
/** 等待工做线程把全部任务执行完毕*/
public void waitFinish() {
synchronized (this) {
isClosed = true;
notifyAll(); //唤醒全部还在getTask()方法中等待任务的工做线程
}
Thread[] threads = new Thread[activeCount()]; //activeCount() 返回该线程组中活动线程的估计值。
int count = enumerate(threads); //enumerate()方法继承自ThreadGroup类,根据活动线程的估计值得到线程组中当前全部活动的工做线程
for(int i =0; i < count; i++) { //等待全部工做线程结束
try {
threads[i].join(); //等待工做线程结束
}catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
/**
* 内部类,工做线程,负责从工做队列中取出任务,并执行
* @author sunnylocus
*/
private class WorkThread extends Thread {
private int id;
public WorkThread(int id) {
//父类构造方法,将线程加入到当前ThreadPool线程组中
super(ThreadPool.this,id+"");
this.id =id;
}
public void run() {
while(! isInterrupted()) { //isInterrupted()方法继承自Thread类,判断线程是否被中断
Runnable task = null;
try {
task = getTask(id); //取出任务
}catch(InterruptedException ex) {
ex.printStackTrace();
}
//若是getTask()返回null或者线程执行getTask()时被中断,则结束此线程
if(task == null) return;
try {
task.run(); //运行任务
}catch(Throwable t) {
t.printStackTrace();
}
}// end while
}// end run
}// end workThread
}
2.测试类 spa
- package com.tdt.test;
-
- import com.tdt.impl.ls.ThreadPool;
-
- public class ThreadPoolTest {
-
- public static void main(String[] args) throws InterruptedException {
- ThreadPool threadPool = new ThreadPool(3); //建立一个有个3工做线程的线程池
- Thread.sleep(500); //休眠500毫秒,以便让线程池中的工做线程所有运行
- //运行任务
- for (int i = 0; i <=5 ; i++) { //建立6个任务
- threadPool.execute(createTask(i));
- }
- threadPool.waitFinish(); //等待全部任务执行完毕
- threadPool.closePool(); //关闭线程池
-
- }
-
- private static Runnable createTask(final int taskID) {
- return new Runnable() {
- public void run() {
- // System.out.println("Task" + taskID + "开始");
- System.out.println("Hello world");
- // System.out.println("Task" + taskID + "结束");
- }
- };
- }
- }
package com.tdt.test;
import com.tdt.impl.ls.ThreadPool;
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
ThreadPool threadPool = new ThreadPool(3); //建立一个有个3工做线程的线程池
Thread.sleep(500); //休眠500毫秒,以便让线程池中的工做线程所有运行
//运行任务
for (int i = 0; i <=5 ; i++) { //建立6个任务
threadPool.execute(createTask(i));
}
threadPool.waitFinish(); //等待全部任务执行完毕
threadPool.closePool(); //关闭线程池
}
private static Runnable createTask(final int taskID) {
return new Runnable() {
public void run() {
// System.out.println("Task" + taskID + "开始");
System.out.println("Hello world");
// System.out.println("Task" + taskID + "结束");
}
};
}
}
结果: .net
- 工做线程0等待任务...
- 工做线程1等待任务...
- 工做线程2等待任务...
-
- 工做线程0开始执行任务...
- Hello world
- 工做线程0等待任务...
-
- 工做线程1开始执行任务...
- Hello world
- 工做线程1等待任务...
-
- 工做线程2开始执行任务...
- Hello world
- 工做线程2等待任务...
-
- 工做线程0开始执行任务...
- Hello world
- 工做线程0等待任务...
-
- 工做线程1开始执行任务...
- Hello world
- 工做线程1等待任务...
-
- 工做线程2开始执行任务...
- Hello world
- 工做线程2等待任务...