自定义线程池(有界队列)

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class UseExecutors {
	public static void main(String[] args) {
		
		ThreadPoolExecutor pool = new ThreadPoolExecutor(
				1,  // coresize
				2,  // maxsize
				60, 
				TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(3)
				,new MyRejected()
				);
		MyTask mt1 = new MyTask(1, "任务1");
		MyTask mt2 = new MyTask(2, "任务2");
		MyTask mt3 = new MyTask(3, "任务3");
		MyTask mt4 = new MyTask(4, "任务4");
		MyTask mt5 = new MyTask(5, "任务5");
		MyTask mt6 = new MyTask(6, "任务6");
		MyTask mt7 = new MyTask(7, "任务7");
		
		pool.execute(mt1);
		pool.execute(mt2);
		pool.execute(mt3);
		pool.execute(mt4);
		pool.execute(mt5);
		pool.execute(mt6);
		pool.execute(mt7);
		
		pool.shutdown();
	}
}
public class MyTask implements Runnable{

	private int taskId;
	private String taskName;
	
	public int getTaskId() {
		return taskId;
	}

	public void setTaskId(int taskId) {
		this.taskId = taskId;
	}

	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}

	public MyTask(int taskId, String taskName) {
		super();
		this.taskId = taskId;
		this.taskName = taskName;
	}

	public String toString() {
		return Integer.toString(this.taskId);
	}
	
	@Override
	public void run() {
		try {
			System.out.println("run taskId = " + this.taskId);
			Thread.sleep(5*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class MyRejected implements RejectedExecutionHandler {
	
	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		// TODO Auto-generated method stub
		System.out.println("自定义处理...");
		System.out.println("当前被拒绝任务为:"+ r.toString());
	}
}
运行结果如下:

run taskId = 1
run taskId = 5
自定义处理...
当前被拒绝任务为:6
自定义处理...
当前被拒绝任务为:7
run taskId = 2
run taskId = 3
run taskId = 4

### 配置BlockingQueue作为任务队列 在Java中自定义线程池时,`ThreadPoolExecutor`允许指定不同的阻塞队列来管理待处理的任务。以下是几种常见的阻塞队列及其适用场景: #### 使用ArrayBlockingQueue 当希望设定一个固定容量的任务队列时可以选择`ArrayBlockingQueue`。这种类型的队列有界队列,适合于需要严格控制最大并发量的应用程序。 ```java import java.util.concurrent.*; public class CustomThreadPool { private final ThreadPoolExecutor executor; public CustomThreadPool() { BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(10); this.executor = new ThreadPoolExecutor( 2, // 核心线程数 4, // 最大线程数 60L, TimeUnit.SECONDS, workQueue ); } } ``` #### 使用LinkedBlockingQueue 对于那些预期会有大量短期任务到来但是又不想让它们占用过多内存的情况来说,`LinkedBlockingQueue`是一个不错的选择。如果不指定期望的最大长度,默认情况下它是无界的,这可能会带来潜在的风险如OutOfMemoryError。 ```java import java.util.concurrent.*; public class CustomThreadPoolWithUnboundedQueue { private final ThreadPoolExecutor executor; public CustomThreadPoolWithUnboundedQueue() { BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(); this.executor = new ThreadPoolExecutor( 2, // 核心线程数 Integer.MAX_VALUE, // 实际应用应避免如此高的上限 60L, TimeUnit.SECONDS, workQueue ); } } ``` #### 使用SynchronousQueue 如果应用程序中的任务几乎总是立即被某个工作线程取走执行而无需排队等待,则可考虑采用`SynchronousQueue`。这类队列实际上并不保存任何元素;每次插入都必须有一个对应的移除操作同时发生。 ```java import java.util.concurrent.*; public class DirectHandoffThreadPool { private final ThreadPoolExecutor executor; public DirectHandoffThreadPool() { BlockingQueue<Runnable> workQueue = new SynchronousQueue<>(); this.executor = new ThreadPoolExecutor( 0, // 不保留核心线程 Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, workQueue ); } } ``` #### 使用PriorityBlockingQueue 为了使某些高优先级的任务能够得到更早的调度机会,可以利用实现了`Comparator`接口的对象配合`PriorityBlockingQueue`一起使用。需要注意的是,由于这是一个无界的延迟队列,因此同样要注意防止内存泄漏问题[^3]。 ```java import java.util.concurrent.*; import java.util.Comparator; import org.example.MyTask; // 假设MyTask实现了Comparable<MyTask> public class PriorityBasedThreadPool { private final ThreadPoolExecutor executor; public PriorityBasedThreadPool() { Comparator<MyTask> comparator = (o1, o2) -> /* 定义比较逻辑 */; BlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<>(11, comparator); this.executor = new ThreadPoolExecutor( 2, // 核心线程数 4, // 最大线程数 60L, TimeUnit.SECONDS, workQueue ); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值