Java并发

This commit is contained in:
罗祥
2019-11-27 16:54:51 +08:00
parent fdb2e9404c
commit 7a257140b7
8 changed files with 472 additions and 22 deletions

View File

@@ -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();
}
}

View File

@@ -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();
}