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 ...
随机推荐
- 关于Yii2中CSS,JS文件的引入心得
js和css的引入 use yii\helpers\Html; 1.全局引入,所有的view生效 /assets/AppAsset.php public $css = [ 'css/site.css' ...
- JEECMS中返回列表跳转的几种方式
1.返回的不是当前类 <span class="tools pull-right"> <button class="btn btn-info" ...
- Leetcode 264. Ugly Number II
Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors ...
- 【BZOJ-3931】网络吞吐量 最短路 + 最大流
3931: [CQOI2015]网络吞吐量 Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 1228 Solved: 524[Submit][Stat ...
- MongoDB安装与启动
我本人电脑是win8系统64位,下载64位的zip包,下载完成后解压缩到D:\MongoDB目录 创建数据库目录D:\MongoDB\data,接下来打开命令行窗口,切换到D:\MongoDB\bin ...
- 使用reids结合wcf实现集群模式下的聊天室功能
1.reids的特点 Redis数据库完全在内存中,使用磁盘仅用于持久性. 相比许多键值数据存储,Redis拥有一套较为丰富的数据类型(字符串,哈希,列表,集合,有序集合),. Redis可以将数据复 ...
- codevs 1229 数字游戏(可重集的全排列)
传送门 Description Lele 最近上课的时候都很无聊,所以他发明了一个数字游戏来打发时间. 这个游戏是这样的,首先,他拿出几张纸片,分别写上0到9之间的任意数字(可重复写某个数字),然后 ...
- POJ 2533 Longest Ordered Subsequence(最长上升子序列(NlogN)
传送门 Description A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subseque ...
- How to set up an FTP server on Ubuntu 14.04
How to set up an FTP server on Ubuntu 14.04 Setting up a fully-functional and highly secure FTP serv ...
- sql 编写横竖表转换
将横表转为竖表,基本思想是: 1)将横表的多条数据,"压"成一条.相当于将这么多条分组,每组"压"成一条数据.利用group by 2) 再对竖表中的列,由特定 ...