Java并发编程-22-处理在执行器中被拒绝的任务

一、被拒绝的任务

1、当我们想结束执行器的执行时,调用shutDown()方法

2、但是,执行器只有等待正在运行的任务或者等待执行任务结束之后,才能真正结束

3、如果在执行器shutDown()之后,发送一个任务给执行器,这个任务会被拒绝


二、RejectedExecutionHandler接口

这个接口只有一个方法

void rejectedExecution(Runnable r, ThreadPoolExecutor executor);

三、测试代码

package com.concurrency.executor;

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

/**
 * 实现RejectedExecutionHandler接口
 * @author Nicholas
 *
 *	实现rejectedExecution方法
 */
public class RejectedTaskController implements RejectedExecutionHandler {

	/**
	 * 打印被拒绝的任务的名称和状态
	 */
	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		System.out.printf(
				"RejectedTaskController : The Task %s has been rejected\n",
				r.toString());

		System.out.printf(
				"RejectedTaskController : The status of the executor is %s\n",
				executor.toString());

		System.out.printf("RejectedTaskController : Terminating %s\n",
				executor.isTerminating());

		System.out.printf("RejectedTaskController : Terminated %s\n",
				executor.isTerminated());
	}
}

package com.concurrency.executor;

import java.util.concurrent.TimeUnit;

public class Task implements Runnable {

	private String name;

	public Task(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println("Task " + name + ": Starting");

		try {
			long duration = (long) (Math.random() * 10);
			System.out
					.printf("Task %s : ReportGenerator : Generating a report during %d seconds\n",
							name, duration);
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Task %s : Ending \n", name);
	}

	@Override
	public String toString() {
		return name;
	}
}

package com.concurrency.executor;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Main {

	public static void main(String[] args) {
		RejectedTaskController rejectedTaskController = new RejectedTaskController();

		ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors
				.newCachedThreadPool();

		//设置rejectedTaskController对象来管理被拒绝的任务
		threadPoolExecutor.setRejectedExecutionHandler(rejectedTaskController);

		System.out.println("Main : starting \n");
		for (int i = 0; i < 3; i++) {
			Task task = new Task("Task -- " + i);
			threadPoolExecutor.submit(task);
		}
		System.out.println("Main : Shutting down the threadPoolExecutor");
		threadPoolExecutor.shutdown();

		//设置用于被拒绝的任务的处理
		System.out.println("Sending another Task...");
		Task task = new Task("RejectedTask");
		threadPoolExecutor.submit(task);

		System.out.println("Main : End");
	}
}

打印的结果:

Main : starting 

Main : Shutting down the threadPoolExecutor
Task Task -- 0: Starting
Sending another Task...
RejectedTaskController : The Task java.util.concurrent.FutureTask@5c647e05 has been rejected
Task Task -- 0 : ReportGenerator : Generating a report during 7 seconds
Task Task -- 2: Starting
Task Task -- 2 : ReportGenerator : Generating a report during 5 seconds
Task Task -- 1: Starting
RejectedTaskController : The status of the executor is java.util.concurrent.ThreadPoolExecutor@1540e19d[Shutting down, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
Task Task -- 1 : ReportGenerator : Generating a report during 2 seconds
RejectedTaskController : Terminating true
RejectedTaskController : Terminated false
Main : End
Task Task -- 1 : Ending 
Task Task -- 2 : Ending 
Task Task -- 0 : Ending 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解关于Java并发编程的CountDownLatch吗? CountDownLatch是Java并发编程非常重要的一个工具类,它可以让某个线程等待其他线程完成后再继续执行。它的作用类似于倒计时门闩,当count值减为0时,所有等待者都会被唤醒。 CountDownLatch是一次性的,也就是说,它的计数器只能使用一次。如果需要重复使用,可以考虑使用CyclicBarrier。 在使用CountDownLatch时,我们需要先创建一个CountDownLatch对象,并指定计数器的初始值。然后在需要等待的线程调用await()方法进行等待,同时在其他线程调用countDown()方法进行计数器的减1操作。 举个例子,假设我们有一个需求:主线程需要等待两个子线程完成后再执行。那么可以这样编写代码: ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程1").start(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程2").start(); System.out.println(Thread.currentThread().getName() + "等待子线程执行完毕"); countDownLatch.await(); System.out.println(Thread.currentThread().getName() + "所有子线程执行完毕,继续执行主线程"); } } ``` 在上面的例子,我们首先创建了一个计数器初始值为2的CountDownLatch对象,然后创建了两个线程分别进行一些操作,并在操作结束后调用countDown()方法进行计数器减1操作。在主线程,我们调用await()方法进行等待,直到计数器减为0时,主线程才会继续执行。 希望能够对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值