Java并发编程核心方法与框架-ScheduledExecutorService的使用
类ScheduledExecutorService的主要作用是可以将定时任务与线程池功能结合。
使用Callable延迟运行(有返回值)
public class MyCallableA implements Callable<String> {
@Override
public String call() throws Exception {
try {
System.out.println("MyCallableA.call() begin " + Thread.currentThread().getName() + System.currentTimeMillis());
Thread.sleep(3000);
System.out.println("MyCallableA.call() end " + Thread.currentThread().getName() + System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
return "returnB";
}
}
public class MyCallableB implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("MyCallableB.call() begin " + Thread.currentThread().getName() + System.currentTimeMillis());
System.out.println("MyCallableB.call() end " + Thread.currentThread().getName() + System.currentTimeMillis());
return "returnA";
}
}
public class Main {
public static void main(String[] args) {
try {
List<Callable<String>> callables = new ArrayList<>();
callables.add(new MyCallableA());
callables.add(new MyCallableB());
int corePoolSize = 2;
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(corePoolSize);
long delay = 4;//延迟4秒开始执行
TimeUnit unit = TimeUnit.SECONDS;
ScheduledFuture<String> scheduledFutureA = scheduledExecutorService.schedule(callables.get(0), delay, unit);
ScheduledFuture<String> scheduledFutureB = scheduledExecutorService.schedule(callables.get(1), delay, unit);
System.out.println("x=" + System.currentTimeMillis());//x=1473037234998
System.out.println("A:" + scheduledFutureA.get());//阻塞,等待任务返回结果
System.out.println("B:" + scheduledFutureB.get());
System.out.println("y=" + System.currentTimeMillis());//y=1473037242004
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行以上代码,控制台输出结果如下:
x=1473037234998
MyCallableA.call() begin pool-1-thread-11473037238999
MyCallableB.call() begin pool-1-thread-21473037238999
MyCallableB.call() end pool-1-thread-21473037238999
MyCallableA.call() end pool-1-thread-11473037242004
A:returnB
B:returnA
y=1473037242004
以上结果为异步执行效果。对main函数进行如下修改:
public class Main {
public static void main(String[] args) {
try {
List<Callable<String>> callables = new ArrayList<>();
callables.add(new MyCallableA());
callables.add(new MyCallableB());
int corePoolSize = 2;
//ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(corePoolSize);
//单个线程
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
long delay = 4;//延迟4秒开始执行
TimeUnit unit = TimeUnit.SECONDS;
ScheduledFuture<String> scheduledFutureA = scheduledExecutorService.schedule(callables.get(0), delay, unit);
ScheduledFuture<String> scheduledFutureB = scheduledExecutorService.schedule(callables.get(1), delay, unit);
System.out.println("x=" + System.currentTimeMillis());//x=1473038300975
System.out.println("A:" + scheduledFutureA.get());
System.out.println("B:" + scheduledFutureB.get());
System.out.println("y=" + System.currentTimeMillis());//y=1473038307984
} catch (Exception e) {
e.printStackTrace();
}
}
}
此时控制台打印结果如下:
x=1473038300975
MyCallableA.call() begin pool-1-thread-11473038304979
MyCallableA.call() end pool-1-thread-11473038307984
A:returnB
MyCallableB.call() begin pool-1-thread-11473038307984
MyCallableB.call() end pool-1-thread-11473038307984
B:returnA
y=1473038307984
此时控制台执行效果为同步执行。方法中的delay参数在多个任务中同时消耗时间,并不是一个任务执行完毕之后再等4秒继续执行。
查看newSingleThreadScheduledExecutor方法源代码:
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
实例化ScheduledThreadPoolExecutor时传入的参数是1,是单任务执行的计划任务池。
使用Runnable延迟运行(无返回值)
public class MyRunnableA implements Runnable {
@Override
public void run() {
try {
System.out.println("MyRunnableA.run() begin " + Thread.currentThread().getName() + System.currentTimeMillis());
Thread.sleep(3000);
System.out.println("MyRunnableA.run() end " + Thread.currentThread().getName() + System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MyRunnableB implements Runnable {
@Override
public void run() {
System.out.println("MyRunnableB.run() begin " + Thread.currentThread().getName() + System.currentTimeMillis());
System.out.println("MyRunnableB.run() end " + Thread.currentThread().getName() + System.currentTimeMillis());
}
}
public class Main {
public static void main(String[] args) {
List<Runnable> runnables = new ArrayList<>();
runnables.add(new MyRunnableA());
runnables.add(new MyRunnableB());
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
System.out.println("x=" + System.currentTimeMillis());
int delay = 5;
TimeUnit unit = TimeUnit.SECONDS;
scheduledExecutorService.schedule(runnables.get(0), delay, unit);
scheduledExecutorService.schedule(runnables.get(1), delay, unit);
System.out.println("y=" + System.currentTimeMillis());
}
}
执行结果如下:
x=1473039288190
y=1473039288191
MyRunnableA.run() begin pool-1-thread-11473039293196
MyRunnableA.run() end pool-1-thread-11473039296199
MyRunnableB.run() begin pool-1-thread-11473039296199
MyRunnableB.run() end pool-1-thread-11473039296199
Java并发编程核心方法与框架-ScheduledExecutorService的使用的更多相关文章
- Java并发编程核心方法与框架-CountDownLatch的使用
Java多线程编程中经常会碰到这样一种场景:某个线程需要等待一个或多个线程操作结束(或达到某种状态)才开始执行.比如裁判员需要等待运动员准备好后才发送开始指令,运动员要等裁判员发送开始指令后才开始比赛 ...
- Java并发编程核心方法与框架-Fork-Join分治编程(一)
在JDK1.7版本中提供了Fork-Join并行执行任务框架,它的主要作用是把大任务分割成若干个小任务,再对每个小任务得到的结果进行汇总,这种开发方法也叫做分治编程,可以极大地利用CPU资源,提高任务 ...
- Java并发编程核心方法与框架-TheadPoolExecutor的使用
类ThreadPoolExecutor最常使用的构造方法是 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAli ...
- Java并发编程核心方法与框架-Semaphore的使用
Semaphore中文含义是信号.信号系统,这个类的主要作用就是限制线程并发数量.如果不限制线程并发数量,CPU资源很快就会被耗尽,每个线程执行的任务会相当缓慢,因为CPU要把时间片分配给不同的线程对 ...
- Java并发编程核心方法与框架-CompletionService的使用
接口CompletionService的功能是以异步的方式一边生产新的任务,一边处理已完成任务的结果,这样可以将执行任务与处理任务分离.使用submit()执行任务,使用take取得已完成的任务,并按 ...
- Java并发编程核心方法与框架-ExecutorService的使用
在ThreadPoolExecutor中使用ExecutorService中的方法 方法invokeAny()和invokeAll()具有阻塞特性 方法invokeAny()取得第一个完成任务的结果值 ...
- Java并发编程核心方法与框架-Future和Callable的使用
Callable接口与Runnable接口对比的主要优点是Callable接口可以通过Future获取返回值.但是Future接口调用get()方法取得结果时是阻塞的,如果调用Future对象的get ...
- Java并发编程核心方法与框架-Executors的使用
合理利用线程池能够带来三个好处 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 提高线程的可管理性.线程是稀 ...
- Java并发编程核心方法与框架-phaser的使用
arriveAndAwaitAdvance()方法 arriveAndAwaitAdvance()作用是当前线程已经到达屏障,在此等待一段时间,等条件满足后继续向下一个屏障执行. public cla ...
随机推荐
- iOS 使用AFN 进行单图和多图上传
图片上传时必要将图片进行压缩,不然会上传失败 1.单张图上传 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManag ...
- AFnetworking3.1的基本使用
听说之后AFHttpWorking版本可能会影响到苹果的审核,今天下了最新版本的AFHttpWorking,并且做了简单的封装,我这里是通过cocoapods下载了两个工具 1=AFHttpWorki ...
- Python 序列通用操作介绍
上一篇:python字符串基础一 下一篇:Python 列表操作简介 序列概览 Python包含6种内置的序列:列表.元组.字符串 .Unicode字符串.buffer对象.xrange对象.在序列中 ...
- [bzoj1787][Ahoi2008]紧急集合
Description 给定一棵大小为的树,有组询问,每组询问给三个点,求到这三个点距离和最小的点及最小距离和. Input 第一行两个数. 接下来行,每行两个数表示到有一条边. 最后行,每行个数,为 ...
- 【bzoj4241】 历史研究
http://www.lydsy.com/JudgeOnline/problem.php?id=4241 (题目链接) 看到题目就联想到了[bzoj2809] Apio2012—dispatching ...
- asp.net接收ajax请求参数时为空的现象
如题,如果使用ajax请求asp.net后台时,如果使用jquery时,默认是添加了请求头,使后台能识别,并能通过Request对象进行获取. 但是如果你使用的是window.XMLHttpReque ...
- DedeCMS Xss+Csrf Getshell \dede\file_manage_control.php
目录 . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 对这个漏洞的利用方式进行简单的概括 . 这个漏洞的利用前提是需要登录到后台进行操作 ...
- AndroidStudio不能解析R的一种可能
最近在做一个APP,突然就无法编译了,提示信息: 查了半天也没找到好的解决办法,最后想起来误删了一个文件,然后Ctrl+Z回退了事,结果不知为何,那个图片文件损坏了,倒是R无法编译出来,方才报错. 记 ...
- NYOJ 16 矩形嵌套(经典动态规划)
传送门 Description 有n个矩形,每个矩形可以用a,b来描述,表示长和宽.矩形X(a,b)可以嵌套在矩形Y(c,d)中当且仅当a<c,b<d或者b<c,a<d(相当于 ...
- (转载)最长递增子序列 O(NlogN)算法
原博文:传送门 最长递增子序列(Longest Increasing Subsequence) 下面我们简记为 LIS. 定义d[k]:长度为k的上升子序列的最末元素,若有多个长度为k的上升子序列,则 ...