Java手写线程池的实现方法

作者:爱吃盐的猿 时间:2023-10-30 12:50:03 

本文实例为大家分享了Java手写线程池的实现代码,供大家参考,具体内容如下

1.线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。

2.线程池简易架构

Java手写线程池的实现方法

3.简易线程池代码(自行优化)


import java.util.List;

/**
* 线程接口
*
* @Author yjian
* @Date 14:49 2017/10/14
**/
public interface IThreadPool {
//加入任务
void execute(Runnable task);

//加入任务
void execute(Runnable[] tasks);

//加入任务
void execute(List<Runnable> tasks);

//销毁线程
void destroy();
}



import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
* 线程实现类(简易实现,自行优化.提供思路)
*
* @Author yjian
* @Date 14:49 2017/10/14
**/
@SuppressWarnings("ALL")
public class ThreadPoolImpl implements IThreadPool {
//默认开启线程个数
static int WORKER_NUMBER = 5;
//完成任务线程数 可见性
static volatile int sumCount = 0;
//任务队列 list非线程安全,可以优化为BlockingQueue
static List<Runnable> taskQueue = new LinkedList<Runnable>();
//线程工作组
WorkerThread[] workThreads;
//原子性
static AtomicLong threadNum = new AtomicLong();

static ThreadPoolImpl threadPool;

//构造方法
public ThreadPoolImpl() {
 this(WORKER_NUMBER);
}

public ThreadPoolImpl(int workerNum) {
 this.WORKER_NUMBER = workerNum;
 //开辟工作线程空间
 workThreads = new WorkerThread[WORKER_NUMBER];
 //开始创建工作线程
 for (int i = 0; i < WORKER_NUMBER; i++) {
  workThreads[i] = new WorkerThread();
  Thread thread = new Thread(workThreads[i], "ThreadPool-worker" + threadNum.incrementAndGet());
  System.out.println("初始化线程数" + (i + 1) + "---------当前线程名称:" + thread.getName());
  thread.start();
 }
}

@Override
public String toString() {
 return "工作线程数量为" + WORKER_NUMBER
   + "已完成的任务数" + sumCount +
   "等待任务数量" + taskQueue.size();
}

//获取线程池
public static IThreadPool getThreadPool() {
 return getThreadPool(WORKER_NUMBER);
}

public static IThreadPool getThreadPool(int workerNum) {
 //容错性,如果小于等于0就默认线程数
 if (workerNum <= 0) {
  workerNum = WORKER_NUMBER;
 }
 if (threadPool == null) {
  threadPool = new ThreadPoolImpl(workerNum);
 }
 return threadPool;
}

@Override
public void execute(Runnable task) {
 synchronized (taskQueue) {
  taskQueue.add(task);
  taskQueue.notifyAll();
 }
}

@Override
public void execute(Runnable[] tasks) {
 synchronized (taskQueue) {
  for (Runnable task : tasks) {
   taskQueue.add(task);
  }
  taskQueue.notifyAll();
 }
}

@Override
public void execute(List<Runnable> tasks) {
 synchronized (taskQueue) {
  for (Runnable task : tasks) {
   taskQueue.add(task);
  }
  taskQueue.notifyAll();
 }
}

@Override
public void destroy() {
 //循环是否还存在任务,如果存在等待20毫秒处理时间
 while (!taskQueue.isEmpty()) {
  try {
   Thread.sleep(20);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 //如果任务队列已处理完成,销毁线程,清空任务
 for (int i = 0; i < WORKER_NUMBER; i++) {
  workThreads[i].setWorkerFlag();
  workThreads[i] = null;
 }
 threadPool = null;
 taskQueue.clear();
}

//创建工作线程池
class WorkerThread extends Thread {
 //用来标识当前线程属于活动可用状态
 private boolean isRunning = true;

@Override
 public void run() {
  Runnable runnable = null;
  //死循环
  while (isRunning) {
   //非线程安全,所以采用同步锁
   synchronized (taskQueue) {
    while (isRunning && taskQueue.isEmpty()) {
     try {
      //如果任务队列为空,等待20毫秒 监听任务到达
      taskQueue.wait(20);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
    //任务队列不为空
    if (!taskQueue.isEmpty()) {
     runnable = taskQueue.remove(0);//获取第一个任务
    }
   }
   if (runnable != null) {
    runnable.run();
   }
   sumCount++;
   runnable = null;
  }
 }

//销毁线程
 public void setWorkerFlag() {
  isRunning = false;
 }
}
}


import java.util.ArrayList;
import java.util.List;

/**
* 测试类
*
* @Author yjian
* @Date 15:37 2017/10/14
**/
public class ThreadPoolTest {

public static void main(String[] args) {
 //获取线程池
 IThreadPool t = ThreadPoolImpl.getThreadPool(20);

List<Runnable> taskList = new ArrayList<Runnable>();
 for (int i = 0; i < 100; i++) {
  taskList.add(new Task());
 }
 //执行任务
 t.execute(taskList);
 System.out.println(t);
 //销毁线程
 t.destroy();
 System.out.println(t);
}

static class Task implements Runnable {

private static volatile int i = 1;

@Override
 public void run() {
  System.out.println("当前处理的线程:" + Thread.currentThread().getName() + " 执行任务" + (i++) + " 完成");
 }
}

}

对spring源码研究的,仔细查看代码用了哪几种spring常用的模式。写程序的规范应该和spring一样。

标签:Java,线程池
0
投稿

猜你喜欢

  • java调用openoffice将office系列文档转换为PDF的示例方法

    2023-11-29 11:42:53
  • Mybatis下的SQL注入漏洞原理及防护方法解析

    2022-06-30 18:38:29
  • 使用JDBC实现数据访问对象层(DAO)代码示例

    2021-11-12 23:33:46
  • Android使用个推实现三方应用的推送功能

    2022-04-16 08:52:46
  • java二维码生成的方法

    2022-08-02 22:07:28
  • 浅谈Spring Boot 整合ActiveMQ的过程

    2022-03-22 05:20:27
  • 一文搞懂Java ScheduledExecutorService的使用

    2022-11-22 14:23:35
  • Android Studio 超级简单的打包生成apk的方法

    2023-08-07 18:57:28
  • java中接口(interface)及使用方法示例

    2021-10-11 10:55:12
  • android中图片的三级缓存cache策略(内存/文件/网络)

    2023-09-04 19:51:59
  • Java源码解析之object类

    2023-11-05 00:46:28
  • Java构造代码块,静态代码块原理与用法实例分析

    2023-11-03 09:03:45
  • Android程序启动时出现黑屏问题的解决方法

    2022-07-06 05:16:39
  • SpringBoot请求处理之常用参数注解介绍与源码分析

    2023-11-10 10:38:12
  • Flutter自定义底部导航栏的方法

    2022-01-10 15:48:33
  • Springboot日志开启SLF4J过程解析

    2022-04-23 01:29:57
  • C#实现贪吃蛇小游戏

    2022-09-28 17:17:59
  • C#下实现创建和删除目录的实例代码

    2021-10-21 16:04:31
  • 实例详解SpringBoot默认的JSON解析方案

    2023-07-21 07:34:20
  • Android三种常见的图片压缩方式

    2022-12-21 06:03:59
  • asp之家 软件编程 m.aspxhome.com