当前位置: 首页 > news >正文

Java并发和多线程3:线程调度和有条件取消调度



在第1篇中“并发框架基本演示样例”。提到了Executors和ThreadPool。
当中。还有个“定时调度”的方法。Executors.newScheduledThreadPool(10)。


// 可运行调度命令(定时+周期性)的线程池,拥有固定的线程数
	// 反复运行,无穷尽
	public static void scheduledThreadPool() {
		int initialDelay = 10;
		int period = 10;
		Executor executor = Executors.newScheduledThreadPool(10);
		ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;
		scheduler.scheduleAtFixedRate(task, initialDelay, period,
				TimeUnit.SECONDS);
	}


这段代码。会一直反复运行,是一种常见的场景。

可是,想到一种“仅仅调度N次”的需求。看了下API,没有提供。
就网上搜索“Java 取消线程调度”,找到了1个问答,就研究了下。
代码演示样例的关键是,使用了线程安全的AtomicInteger和通用同步工具CountDownLatch。

核心逻辑就是,当超过了最大任务数N的时候,取消Future中的任务,countDownLatch中的计数器-1,变为0,“countDownLatch.await()”线程堵塞结束
countDownLatch.countDown();
关于CountDownLatch的进一步介绍,请參考第4篇。

package cn.fansunion.executorframework;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


//有条件地。取消调度
public class ConditionCancelSchedulerDemo {


	public static Runnable task = new Runnable() {
		@Override
		public void run() {
			System.out.println("Execute a task");
		}
	};


	// 可运行调度命令(定时+周期性)的线程池,拥有固定的线程数
	// 反复运行,无穷尽
	public static void scheduledThreadPool() {
		int initialDelay = 10;
		int period = 10;
		Executor executor = Executors.newScheduledThreadPool(10);
		ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;
		scheduler.scheduleAtFixedRate(task, initialDelay, period,
				TimeUnit.SECONDS);
	}


	public static void main(String[] args) throws Exception {
		scheduledThreadPool();
		conditionCancelScheduler();
	}


	private static void conditionCancelScheduler() throws InterruptedException {
		final String jobID = "my_job_1";
		final AtomicInteger count = new AtomicInteger(0);
		final Map<String, Future> futures = new HashMap<>();
		// 最多运行10个任务
		final int maxTaskSize = 10;
		// CountDownLatch的很多其它使用方法,请參考CountDownLatchDemo
		final CountDownLatch countDownLatch = new CountDownLatch(1);
		ScheduledExecutorService scheduler = Executors
				.newSingleThreadScheduledExecutor();


		Future future = scheduler.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				System.out.println(count.getAndIncrement());
				// 当调度运行,第maxTaskSize+1个任务的时候,取消Future中的任务。第11个任务
				if (count.get() > maxTaskSize) {
					System.out.println("a");
					Future f = futures.get(jobID);
					if (f != null) {
						f.cancel(true);
					}
					// countDownLatch中的计数器-1,变为0
					// “countDownLatch.await()”线程堵塞结束
					countDownLatch.countDown();
				}
			}
		}, 0, 1, TimeUnit.SECONDS);


		futures.put(jobID, future);
		countDownLatch.await();


		scheduler.shutdown();
	}
}




很多其它代码演示样例:
http://git.oschina.net/fansunion/Concurrent(逐步更新中)


參考资料:
java并发编程-Executor框架
http://www.iteye.com/topic/366591


有条件地终止 ScheduledExecutorService 中运行的定时任务
http://www.oschina.net/question/1158769_119659?sort=time


JDK API 文档

转载于:https://www.cnblogs.com/jzdwajue/p/7010134.html

相关文章:

  • Android之使用Http协议实现文件上传功能
  • poi API大全
  • Authentication和Authrization(上)
  • std::bind()图解
  • perl概述
  • Thinkphp中在本地测试很好,在服务器上出错,有可能是因为debug缓存的问题
  • perl入门--语法和结构(1)
  • 6月15日云栖精选夜读:阿里配管专家解读:如何最优成本搭建非标准的iOS构建集群...
  • Android下实现电话号码归属地的查询
  • 【转】设计模式总结
  • 21、Java并发性和多线程-Java中的锁
  • 让我有勇气热烈拥抱最后的结局—leo鉴书(14)
  • c++ -- 面向对象程序设计
  • Android下使用Http协议实现多线程断点续传下载
  • HDOJ 5296 Annoying problem LCA+数据结构
  • ----------
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Akka系列(七):Actor持久化之Akka persistence
  • Eureka 2.0 开源流产,真的对你影响很大吗?
  • FineReport中如何实现自动滚屏效果
  • mysql常用命令汇总
  • php面试题 汇集2
  • Python爬虫--- 1.3 BS4库的解析器
  • rabbitmq延迟消息示例
  • 阿里研究院入选中国企业智库系统影响力榜
  • 反思总结然后整装待发
  • 分布式任务队列Celery
  • 推荐一个React的管理后台框架
  • 我感觉这是史上最牛的防sql注入方法类
  • 优化 Vue 项目编译文件大小
  • 在Mac OS X上安装 Ruby运行环境
  • 责任链模式的两种实现
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • (¥1011)-(一千零一拾一元整)输出
  • (C++20) consteval立即函数
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (附源码)基于SSM多源异构数据关联技术构建智能校园-计算机毕设 64366
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)
  • (转) 深度模型优化性能 调参
  • (转)winform之ListView
  • (转)视频码率,帧率和分辨率的联系与区别
  • ..回顾17,展望18
  • .net 7 上传文件踩坑
  • .Net core 6.0 升8.0
  • .net framwork4.6操作MySQL报错Character set ‘utf8mb3‘ is not supported 解决方法
  • .NET HttpWebRequest、WebClient、HttpClient
  • @Autowired标签与 @Resource标签 的区别
  • [CSS]CSS 字体属性
  • [ES-5.6.12] x-pack ssl
  • [ffmpeg] x264 配置参数解析
  • [Linux](15)线程基础,线程控制,线程的互斥与同步
  • [MySQL]视图索引以及连接查询案列
  • [NOIP2018 PJ T4]对称二叉树
  • [objective-c]关于KVC--KVO--KVB