JAVA并发编程4

说明:先上代码,笔记后续补充。
public class ScheduleTest1 {

private static long start;

private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

/**
* 由于timer是单线程的,问题很多
* 如果用timer.schedule加上sleep之后的输出是1001 6005
* 第一个线程的sleep会影响第二个线程
*如果第一个线程挂掉了,则第二个线程不会执行
*而且timer是和系统时间相关的
*
* 使用executorService不会出现以上的问题
*
* @param args
*/
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
// System.out.println(System.currentTimeMillis()-start);
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
throw new RuntimeException();
}
};

TimerTask task1 = new TimerTask() {
@Override
public void run() {
System.out.println(System.currentTimeMillis()-start);
}
};

Timer timer = new Timer();
start = System.currentTimeMillis();
// //1s后执行
// timer.schedule(task,1000);
// //3s后执行
// timer.schedule(task1,3000);

executorService.schedule(task,1000, TimeUnit.MILLISECONDS);
executorService.schedule(task1,3000, TimeUnit.MILLISECONDS);
}
}
posted @ 2018-04-22 22:21  Gggoblin  阅读(103)  评论(0编辑  收藏  举报