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 ...
随机推荐
- java.lang.Exception: No runnable methods
java.lang.Exception: No runnable methods at org.junit.runners.BlockJUnit4ClassRunner.validateInstanc ...
- 自定义UITabBar的两种方式
开发中,经常会遇到各种各样的奇葩设计要求,因为apple提供的UITabBar样式单一,只是简单的"图片+文字"样式,高度49又不可以改变.自定义UITabBar成为了唯一的出路. ...
- js 中 == 和=== 有什么区别?
第一个是相等符:第二个全等符: 其中第一个在比较的时候,会进行类型转换,而第二个则不会, alert('55' == 55);//truealert('55' === 55);//false
- js-JavaScript高级程序设计学习笔记2
第四章 变量.作用域和内存问题 1.ES变量包含两种不同数据类型的值--基本类型值(5种基本数据类型)和引用类型值(保存在内存中的对象,所有引用类型值都是Object的实例) 2.只能给引用类型值动态 ...
- Leetcode Integer Replacement
Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If ...
- hdfs创建级联文件夹
一个文件夹 hdfs dfs -mkdir /out /一定要有 级联 hdfs dfs -mkdir -p /out/ags 需要家-p
- 下载Spring的jar包的方法
- Gulp.js----比Grunt更易用的前端构建工具
Gulp.js----比Grunt更易用的前端构建工具 Grunt一直是前端构建工具,然而他也不是毫无缺陷的,gulp的作者 Eric Schoffstall 在他介绍 gulp.js 的 prese ...
- [iOS Hybrid实践:UIWebView中Html中用JS调用OC方法,OC执行JS代码]
原理: 1.JS调用OC 每次webview执行跳转时都会被iOS给拦截,执行下面函数获得系统允许. 因此可以根据跳转信息转给系统,执行相应功能,比如打开相册等. // 网页中的每一个请求都会被触发 ...
- 【问题】R文件报错原因及解决办法 (转)
错误如图.下面是几种解决方法(网上搜集的). 1.如果是导入项目出现这个问题,一般是R文件没有更新造成(据说导入项目,R不会自动更新).可以Project——clean以下,R文件会重新生成. 2.选 ...