手写线程池

package Juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * java多线程的方式4种
 * 1.继承Thread类
 * 2.实现runable接口 
 * 3.实现collable接口
 * 4.从线程池获取
 *		System.out.println(Runtime.getRuntime().availableProcessors());//电脑核数
 *  线程池运行原理+7大参数:
 *
 *
 */
public class MyThreadPool {

	public static void main(String[] args) {
		ExecutorService threadPool = new ThreadPoolExecutor(
				2,
				5,//cpu密集型没有阻塞max=(cpu核数+1)计算减少cpu上下文切换,Io密集型max=(cpu核数*2)访问数据库,cpu核数=x*(0.8-0.9)
				1L,
				TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(3), //有界阻塞队列
				Executors.defaultThreadFactory(),//线程池工厂
				new ThreadPoolExecutor.DiscardPolicy());//拒绝策略:4种->
														//AbortPolicy();超过max+阻塞队列抛出异常
													  //CallerRunsPolicy();超出max+阻塞队列把请求退回给调用者
														//DiscardOldestPolicy();超出max+阻塞队列把请求任务种最久的抛弃
														//DiscardPolicy();超出max+阻塞队列把超出的请求丢弃
		try {
			//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
			for (int i = 1; i <=8; i++) {
				threadPool.execute(()->{
					System.out.println(Thread.currentThread().getName()+"\t"+"办理业务");
				});
				//暂停一会儿线程
			}
			
		} finally {
			threadPool.shutdown();
		
		}
	}

	/**
	 * JDK集成,一般不用原因:有界队列
	 * )FixedThreadPool 和 SingleThreadPool:   
	 * 允许的请求队列长度为 Integer.MAX_VALUE,
	 * 可能会堆积大量的请求,从而导致 OOM。
	 *  2)CachedThreadPool 和 ScheduledThreadPool:
	 *  允许的创建线程数量为 Integer.MAX_VALUE,
	 * 可能会创建大量的线程,从而导致 OOM。 
	 */
	public static void threadPoolInit() {
		//ExecutorService threadPool = Executors.newFixedThreadPool(5);
		ExecutorService threadPool = Executors.newSingleThreadExecutor();  //7种常用的3次
		//ExecutorService threadPool = Executors.newCachedThreadPool();
		
			try {
				//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
				for (int i = 1; i <=10; i++) {
					threadPool.execute(()->{
						System.out.println(Thread.currentThread().getName()+"\t"+"办理业务");
					});
					//暂停一会儿线程
					//try{TimeUnit.MILLISECONDS.sleep(200);}catch (Exception e){e.printStackTrace();}
				}
				
			} finally {
				threadPool.shutdown();
			}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
手写一个简单的线程池,你可以按照以下步骤进行: 1. 创建一个任务队列,用于存储待执行的任务。 2. 创建一个固定数量的线程池,用于执行任务。 3. 每当有任务提交到线程池时,将任务添加到任务队列中。 4. 线程池中的每个线程会不断从任务队列中获取任务并执行。 5. 执行完一个任务后,线程继续从任务队列中获取下一个任务,并重复执行,直到任务队列为空。 下面是一个简单的 Java 代码示例: ```java import java.util.LinkedList; import java.util.Queue; public class ThreadPool { private final int poolSize; private final WorkerThread[] workerThreads; private final Queue<Runnable> taskQueue; public ThreadPool(int poolSize) { this.poolSize = poolSize; this.taskQueue = new LinkedList<>(); this.workerThreads = new WorkerThread[poolSize]; for (int i = 0; i < poolSize; i++) { workerThreads[i] = new WorkerThread(); workerThreads[i].start(); } } public void submit(Runnable task) { synchronized (taskQueue) { taskQueue.add(task); taskQueue.notify(); // 唤醒等待的线程 } } private class WorkerThread extends Thread { @Override public void run() { while (true) { Runnable task; synchronized (taskQueue) { while (taskQueue.isEmpty()) { try { taskQueue.wait(); // 等待新任务的到来 } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } task = taskQueue.poll(); } try { task.run(); // 执行任务 } catch (RuntimeException e) { // 异常处理 } } } } // 使用示例 public static void main(String[] args) { ThreadPool threadPool = new ThreadPool(5); for (int i = 0; i < 10; i++) { final int index = i; threadPool.submit(() -> { System.out.println("Task " + index + " is running."); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Task " + index + " is complete."); }); } } } ``` 上述代码中,首先创建了一个任务队列 `taskQueue`,用于存储待执行的任务。然后创建了固定数量的线程池 `workerThreads`,每个线程会不断从任务队列中获取任务并执行。`ThreadPool` 类提供了 `submit` 方法,用于向线程池提交任务。 在 `main` 方法中,我们创建了一个大小为 5 的线程池,并向线程池提交了 10 个任务,每个任务会打印一段文字,并睡眠一秒钟模拟执行任务的耗时。你可以根据实际需求调整线程池的大小和任务的数量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值