1 package com.lovo.threadpool;
2
3 public class ThreadOfPool extends Thread{
4 private Runnable task = null;
5 private ThreadPool threadPool;
6 private boolean stop = false;//线程状态
7 public ThreadOfPool() {
8 }
9 public ThreadOfPool(ThreadPool threadPool) {
10 this.threadPool = threadPool;
11 }
12 /**
13 * 给线程分配指定的任务
14 * @param task
15 */
16 public synchronized void setTask(Runnable task) {
17 this.task = task;
18 notify();
19 }
20 /**
21 * 线程执行
22 */
23 private synchronized void executeTask() {
24 while (!stop) {
25 while (!stop && task == null) {
26 try {
27 wait();
28 } catch (InterruptedException e) {
29 stop = true;
30 }
31 }
32 if (task != null) {
33 task.run();
34 task = null;
35 threadPool.free(this);
36 }
37 }
38 }
39 @Override
40 public void run() {
41 executeTask();
42 }
43 public Runnable getTask() {
44 return task;
45 }
46 public void setStop(boolean stop) {
47 this.stop = stop;
48 }
49
50 }
1 package com.lovo.threadpool;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class ThreadPool {
7 private List<Thread> freeThreads = new ArrayList<Thread>();//空闲线程(可用)
8 private List<Thread> usingThreads = new ArrayList<Thread>();//正在被使用的线程(不可用)
9 private int POOL_SIZE = 5;
10 public ThreadPool(){
11 this(POOL_SIZE);
12 }
13 public ThreadPool(int num){
14 POOL_SIZE = num;
15 for (int i = 0; i < POOL_SIZE; i++) {
16 ThreadOfPool tempThread = new ThreadOfPool(this);
17 tempThread.start();
18 freeThreads.add(tempThread);
19 }
20 }
21 /**
22 * 分配一个线程
23 * @param t
24 */
25 public synchronized void execute(Runnable t) {
26 while (freeThreads.isEmpty()) {
27 // System.out.println("线程池繁忙,请等待!");
28 try {
29 wait();
30 } catch (InterruptedException e) {
31 e.printStackTrace();
32 }
33 }
34 ThreadOfPool tempthread= (ThreadOfPool) freeThreads.remove(freeThreads.size() - 1);
35 usingThreads.add(tempthread);
36 tempthread.setTask(t);
37 }
38 /**
39 * 分配的线程用完后的回收处理
40 * @param threadOfPool
41 */
42 public synchronized void free(ThreadOfPool threadOfPool) {
43 usingThreads.remove(threadOfPool);
44 freeThreads.add(threadOfPool);
45 notify();
46 }
47 /**
48 * 关闭线程池
49 */
50 public void close() {
51 while (freeThreads.size() < POOL_SIZE) {}
52 for (Thread thread : freeThreads) {
53 thread.interrupt();
54 }
55 }
56 }