首页 > 代码库 > 初次学习多线程——自己写的一个线程池
初次学习多线程——自己写的一个线程池
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 task15 */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 @Override40 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 t24 */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 threadOfPool41 */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 }
初次学习多线程——自己写的一个线程池
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。