一、前言
TaskDecorator是一个执行回调方法的装饰器,主要应用于传递上下文,或者提供任务的监控/统计信息,可以用于处理子线程与主线程间数据传递的问题。
二、开发示例
1.自定义TaskDecorator
import org.springframework.core.task.TaskDecorator;public class MyTaskDecorator implements TaskDecorator {@Overridepublic Runnable decorate(Runnable runnable) {return ()->{System.out.println("线程执行前,资源设置。。。。");runnable.run();System.out.println("线程执行后,资源清理。。。。");};}
}
2. 自定义线程池,设置TaskDecorator
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setTaskDecorator(new MyTaskDecorator());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();executor.execute(()->{System.out.println("我是一个测试线程。。。");
});executor.shutdown();