该线程池实现完全是通过jdbc连接池的思想而来的,事实上真正线程池别人是怎么实现的我也不知道,但我的可行。。。这个线程池是写死了的,只有固定的线程可用,仅作学习之用。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; } @Override public synchronized void start() { if (!isStart) { isStart = true; Stop = false; super.start(); } else { notify(); } } @Override public 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 } @Override public 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()); } } }
java线程池的简单实现
最新推荐文章于 2024-06-30 15:04:58 发布