JAVA并发编程4

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

private static long start;

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

/**
* 如果用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);
}
}

猜你喜欢

转载自www.cnblogs.com/sleepy-goblin/p/8910045.html