自定义java 线程池



为什么要建立线程池?

 

在多线程项目中,如果建立的线程过多,反而可能导致运行速度大大减慢,这是由于线程建立所花费的时间和资源都比较多。
所以我们在多线程中必须很好地来管理线程, 在很好利用多线程能“同步工作”的好处之外,更有效地提高程序运行速度。

 

线程池是什么?

 

线程池是指具有固定数量的线程组成的一种组件。这些线程用来循环执行多个应用逻辑。

 

怎么建立线程池?

 

线程池主要包括4个部分,它们是:
1. 线程管理
 

主要是用来建立,启动,销毁工作线程和把工作任务加入工作线程。

 

2. 工作线程
 

它是真正的线程类,运行工作任务。

 

3. 工作队列
 

它是用来封装线程的容器。


4. 工作任务
 

它是实现应用逻辑的具体类。


 流程图:



线程管理类:

                  Java代码
<span style="color: rgb(51, 102, 255);">import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * ThreadPoolManager.java
 *
 */

/**
 * the thread pool manager, is responsible for starting and stopping the work thread.
 * 
 * @author  gray
 * @version 1.0
 */
public class ThreadPoolManager {

	private static final int DEFAULT_POOL_SIZE = 4;
	private List<WorkThread> threadPool;
	private Queue<Task> taskQueue;
	private int poolSize;
	
	public ThreadPoolManager() {
		this(DEFAULT_POOL_SIZE);
	}
	
	public ThreadPoolManager(int poolSize) {
		if(poolSize <= 0) {
			this.poolSize = DEFAULT_POOL_SIZE;
		}else {
			this.poolSize = poolSize;
		}
		threadPool = new ArrayList<WorkThread>(this.poolSize);
		taskQueue = new ConcurrentLinkedQueue<Task>();
		startup();
	}
	
	public void startup() {
		System.out.println("start work thread...");
		synchronized(taskQueue) {
			for(int i = 0; i < this.poolSize; i++) {
				WorkThread workThread = new WorkThread(taskQueue);
				threadPool.add(workThread);
				workThread.start();
			}
		}
	}
	
	public void shutdown() {
		System.out.println("shutdown work thread...");
		synchronized(taskQueue) {
			for(int i = 0; i < this.poolSize; i++) {
				threadPool.get(i).shutdown();
			}			
			
			System.out.println("done...");
		}
	}
	
	public void addTask(Task task) {
		synchronized(taskQueue) {
			taskQueue.add(task);
			taskQueue.notify();
		}
	}
}</span>

工作线程类:

Java代码
<span style="color: rgb(51, 102, 255);">import java.util.Queue;

/**
 * WorkThread.java
 *
 */

/**
 * the work thread used pull the task of task queue, and execute it.
 * 
 * @author  gray
 * @version 1.0
 */
public class WorkThread extends Thread {

	private boolean shutdown = false;
	private Queue<Task> queue;
	
	public WorkThread(Queue<Task> queue) {
		this.queue = queue;
	}
	
	public void run() {
		while(!shutdown) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println(Thread.currentThread() + " is running...");
			synchronized(queue) {
				if(!queue.isEmpty()) {
					Task task = queue.poll();
					task.execute();
				}else {
					try {
						queue.wait(1000);
						System.out.println(Thread.currentThread() + " wait...");
					}catch(InterruptedException e) {
						
					}
				}
			}
		}
	}
	
	public void shutdown() {
		shutdown = true;
	}
}</span>

工作任务接口:
<span style="color: rgb(51, 102, 255);">/**
 * Task.java
 *
 */

/**
 * The task want to execute.
 * 
 * @author  gray
 * @version 1.0
 */
public interface Task {

	public void execute();
}</span>


工作任务类:
<span style="color: rgb(51, 102, 255);">/**
 * SimpleTask.java
 *
 */

/**
 * @author  gray
 * @version 1.0
 */
public class SimpleTask implements Task {

	/* (non-Javadoc)
	 * @see Task#execute()
	 */
	public void execute() {
		System.out.println(Thread.currentThread());
	}

}</span>

线程池测试类:

Java代码

<span style="color: rgb(51, 102, 255);">/**
 * ThreadPoolDemo.java
 *
 */

/**
 * @author  gray
 * @version 1.0
 */
public class ThreadPoolDemo {

	public static void main(String[] args) {
		ThreadPoolManager threadMg = new ThreadPoolManager();
		
		for(int i = 0; i < 50; i++) {
			threadMg.addTask(new SimpleTask());
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		threadMg.shutdown();
	}	
}</span>


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以通过自定义ThreadPoolExecutor类来创建自己的线程池。ThreadPoolExecutor类是ExecutorService接口的一个实现,它提供了一个灵活的线程池管理机制。 要自定义ThreadPoolExecutor线程池,我们需要使用ThreadPoolExecutor类的构造函数来创建一个实例,并设置一些参数来配置线程池的行为。下面是一个示例代码: ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class CustomThreadPoolExecutor { public static void main(String[] args) { // 创建一个阻塞队列,用于存放待执行的任务 BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(10); // 创建自定义线程池 ThreadPoolExecutor executor = new ThreadPoolExecutor( 5, // 核心线程数 10, // 最大线程数 1, // 空闲线程存活时间 TimeUnit.MINUTES, // 时间单位 queue // 阻塞队列 ); // 添加任务到线程池中 for (int i = 0; i < 20; i++) { executor.execute(() -> { System.out.println("执行任务"); }); } // 关闭线程池 executor.shutdown(); } } ``` 在上面的示例代码中,我们使用了一个LinkedBlockingQueue作为阻塞队列来存放待执行的任务。然后,我们创建了一个ThreadPoolExecutor实例,并设置了核心线程数为5,最大线程数为10,空闲线程存活时间为1分钟。接下来,我们通过execute方法向线程池提交了20个任务。 最后,记得要调用executor.shutdown()方法来关闭线程池,以确保所有任务执行完毕并释放资源。 通过自定义ThreadPoolExecutor类,我们可以根据实际需求来设置线程池的参数,并且可以根据需要灵活地处理提交的任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值