Java并发
This commit is contained in:
@@ -11,15 +11,22 @@ public class J1_ThreadPool {
|
||||
static class Task implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println(Thread.currentThread().getName() + "正在执行");
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
System.out.println(Thread.currentThread().getName() + "正在执行");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
// 提交任务到线程池
|
||||
executorService.submit(new Task());
|
||||
}
|
||||
// 关闭线程池,此时不再接受新任务,但仍会等待原有的任务执行完成,如果想要立即关闭,则可以使用shutdownNow()
|
||||
executorService.shutdown();
|
||||
}
|
||||
}
|
||||
|
@@ -33,12 +33,13 @@ public class J2_ScheduledTask {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 为避免相互间的影响,以下各种场景最好分别测试:
|
||||
ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
|
||||
// 只执行一次
|
||||
pool.schedule(new Task("schedule"), 2, TimeUnit.SECONDS);
|
||||
// 指定2秒为固定周期执行,如果项目执行耗时5秒,则项目结束后立马执行下一次任务,所以输出的时间间隔为5秒
|
||||
// 指定2秒为固定周期执行,因为项目执行耗时5秒,此时项目结束会立马执行下一次任务,所以输出的时间间隔为5秒
|
||||
pool.scheduleAtFixedRate(new Task("FixedRate"), 0, 2, TimeUnit.SECONDS);
|
||||
// 总是在上一次项目结束后间隔指定周期执行,所以项目耗时5秒,还需要间隔2秒执行,所以输出的时间间隔为7秒
|
||||
// 总是在上一次项目结束后间隔指定周期执行,因为项目耗时5秒,还需要间隔2秒执行,所以输出的时间间隔为7秒
|
||||
pool.scheduleWithFixedDelay(new Task("WithFixedDelay"), 0, 2, TimeUnit.SECONDS);
|
||||
// pool.shutdown();
|
||||
}
|
||||
|
Reference in New Issue
Block a user