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 ...
随机推荐
- 【faster-rcnn】训练自己的数据——修改图片格式、类别
修改图片格式 matlab代码 其实内部一些代码是用了rbg的fast-rcnn代码的. \datasets\VOCdevkit2007\VOCcode\VOCinit.m里面,查找'jpg',改成' ...
- 【bzoj3675】 Apio2014—序列分割
http://www.lydsy.com/JudgeOnline/problem.php?id=3675 (题目链接) 题意 给出一个包含n个非负整数的序列,要求将其分割成k+1个序列,每次分割可以获 ...
- 网易免费/付费163企业邮smtp服务器地址
免费:smtp.ym.163.com 25/pop.ym.163.com 110 付费:smtp.qiye.163.com 25/pop.qiye.163.com 110
- PowerDesigner中Table视图同时显示Code和Name
如题,实现如下的效果: 解决方法: 1.Tools-Display Preference 然后选中Code移到最上面
- Bzoj2118 墨墨的等式
Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 1488 Solved: 578 Description 墨墨突然对等式很感兴趣,他正在研究a1x1+ ...
- MySQL备份方式简介
MySQL备份的方式主要分为两种: 文本格式备份: 命令:mysqldump 转储文件:dump file 主要内容:数据库结构及数据(create talbe /insert) 二进制备份:这类备份 ...
- JavaScript碰到的几个方法
=>isNaN() 函数用于检查其参数|是否|是|非数字值. 绕吧,我给它断个句,别一不小心看叉了 百度百科告诉我们,NaN,是Not a Number的缩写 所以, alert(isNaN(1 ...
- MOOCULUS微积分-2: 数列与级数学习笔记 1. Sequences
此课程(MOOCULUS-2 "Sequences and Series")由Ohio State University于2014年在Coursera平台讲授. PDF格式教材下载 ...
- django 模板中url的处理
在模板中直接添加‘/home’这样的链接是十分不推荐的,因为这是一个相对的链接,在不同网页中打开可能会返回不一样的结果. 所以推荐的是 <a href="{{ object.get_a ...
- python获取知乎日报另存为txt文件
前言 拿来练手的,比较简单(且有bug),欢迎交流~ 功能介绍 抓取当日的知乎日报的内容,并将每篇博文另存为一个txt文件,集中放在一个文件夹下,文件夹名字为当日时间. 使用的库 re,Beautif ...