package com.lxw.thread;import java.util.LinkedList;public class ThreadPool {private LinkedList<MyThread> list = new LinkedList<MyThread>();//預設線程池數量private static final int deflautPoolSize = 10;public ThreadPool(int Poolsize) {for (int i = 0; i < Poolsize; i++) {list.add(new MyThread());}}public ThreadPool() {this(deflautPoolSize);}public synchronized void destoryAllThread() {for (int i = 0; i < list.size(); i++) {list.get(i).setStop(true);}notifyAll();}//獲得線程池中的一個可用線程,你傳個實現了Runnable介面的對象,調用start方法,會調用這個對象的run方法public Thread getThread(Runnable r) {if (list.size() != 0) {MyThread thread = list.removeFirst();thread.setRunnable(r);return thread;}throw new RuntimeException("線程池中沒有線程可供使用");}/* * 一份特殊的線程,是線程池中可以重複利用的線程 * 一般增強一個類有三種方法:1,成為其子類 2,裝飾模式(jdk中的IO流就是) 3,代理模式 * 本例子用的方法為第一種 */class MyThread extends Thread {private Runnable runnable;private boolean Stop = true;private boolean isStart = false;public void setStop(boolean stop) {Stop = stop;start();}private void setRunnable(Runnable r) {runnable = r;}@Overridepublic synchronized void start() {if (!isStart) {isStart = true;Stop = false;super.start();} else {notify();}}@Overridepublic synchronized void run() {while (!Stop) {runnable.run();try {list.addLast(this);this.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}}}//測試mian方法public static void main(String[] args) throws InterruptedException {ThreadPool threadPool = new ThreadPool(3);Thread t1 = threadPool.getThread(new Testthread(5));t1.start();threadPool.getThread(new Testthread(15)).start();threadPool.getThread(new Testthread(25)).start();Thread.sleep(5000);threadPool.getThread(new Testthread(35)).start();threadPool.getThread(new Testthread(45)).start();Thread.sleep(3000);threadPool.getThread(new Testthread(35)).start();threadPool.getThread(new Testthread(45)).start();threadPool.getThread(new Testthread(35)).start();Thread.sleep(3000);threadPool.destoryAllThread();}/* * 一個普通的線程,測試所用 */static class Testthread implements Runnable {private int count;public Testthread(int count) {this.count = count;}public Testthread() {super();// TODO Auto-generated constructor stub}@Overridepublic void run() {System.out.println(count++ + "");System.out.println(count++ + "");System.out.println(count++ + "");System.out.println(count++ + "");System.out.println("threadName:" + Thread.currentThread().getName());}}}
該線程池實現完全是通過jdbc串連池的思想而來的,事實上真正線程池別人是怎麼實現的我也不知道,但我的可行。。。這個線程池是寫死了的,只有固定的線程可用,僅作學習之用。