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

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(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

你可能感兴趣的:(java)