一、创建新的线程
new Thread(() -> System.out.println("Single Thread Run.............")).start();
二、ExecutorService管理无返回值的线程(
ExecutorService+runnable)
Executos支持运行异步任务,通常管理一个线程池,这样一来我们就不需要手动去创建新的线程。
“尝试关闭ExecutorService”这句话输出后,过了4s后“thread managed by executorservice............”才被输出
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("thread managed by executorservice............");
});
try {
System.out.println("\n\n\n\n\n\n\n\n尝试关闭ExecutorService");
executorService.shutdown();
//指定一段时间温和关闭
executorService.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.out.println("任务中断。。。。。。。。。。。。");
}
finally {
if (!executorService.isTerminated()) {
System.out.println("结束未完成的任务。。。。。。。。。。。");
}
executorService.shutdownNow();
System.out.println("ExecutorService被停止。。。。。。。。。。。");
}
注:
Java进程从没有停止!Executors必须显式的停止-否则它们将持续监听新的任务。如果执行executorService.shutdown();时任务未终止,会报java.lang.InterruptedException: sleep interrupted异常
三、ExecutorService管理有返回值的线程(ExecutorService+callable+future)
Callable<String>callable = ()-> {
TimeUnit.SECONDS.sleep(4);
return "managed by executor and have result to return";
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(callable);
try {
String result = future.get();
System.out.print("\n\n\n\n\n\n\n\nresult: " + result);
} catch (Exception e) {
e.printStackTrace();
}
注:future.get()是一个阻塞的方法,大约4s之后值才输出出来
运行结果:
四、Executors批量处理多个callable并返回所有callable的运行结果(Executor+callable+future+invokeAll)
private static void testInvokeAll(){
ExecutorService executorService = Executors.newWorkStealingPool();
List<Callable<String>> callables = Arrays.asList(getCallable("download apk...........", 4),getCallable("download files...........", 10),getCallable("download pictures...........", 6));
try {
executorService.invokeAll(callables)
.stream()
.map(future ->{
try{
return future.get();
}catch (Exception e) {
e.printStackTrace();
return "";
}
})
.forEach(System.out::println);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static Callable<String> getCallable(String s,long time){
Callable<String> callable = ()-> {
TimeUnit.SECONDS.sleep(time);
return s;
};
return callable;
}
注:三个任务执行的时间分别为4s、10s、6s,invokeAll会在所有的任务都执行完也就是10s之后才输出结果
运行结果:
五、Executors批量处理多个callable并返回运行最快的callable的运行结果(Executor+invokeAny)
long startTime = System.currentTimeMillis();
ExecutorService executorService = Executors.newWorkStealingPool();
List<Callable<String>> callables = Arrays.asList(getCallable("download apk...........", 4),getCallable("download files...........", 10),getCallable("download pictures...........", 6));
try {
String result = executorService.invokeAny(callables);
System.out.println("执行..."+result+"...花了........."+(System.currentTimeMillis() - startTime)/1000 +"s..............");
} catch (Exception e) {
e.printStackTrace();
}
注:invokeAll返回集合中所有callable的结果,invokeAny只返回一个值,即运行最快的那个callable的值
运行结果:
六、Executors延迟一段时间执行任务(executorService.schedule(task,time,timeUnit))
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.schedule(() -> System.out.println("test delay runnable.............."), 3, TimeUnit.SECONDS);
延迟3s后执行task,结果3s后才输出
运行结果:
七、
Executors以固定时间执行任务(
executorService.scheduleAtFixedRate()
)
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> System.out.println("test fixed delay runnable.............."), 3,5, TimeUnit.SECONDS);
3s后第一次输出结果,然后每5s执行一次任务
注:
scheduleAtFixedRate()
并不考虑任务的实际用时。所以,如果你指定了一个period为1分钟而任务需要执行2分钟,那么线程池为了性能会更快的执行。
运行结果:
八、Executors两次任务之间以固定的间隔执行(
executorService.
scheduleWithFixedDelay())
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(() ->
{System.out.println("test fixed delay runnable..............");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}},
3,5, TimeUnit.SECONDS);
注:该方法是在3s后第一次执行任务输出结果,然后在任务执行完后的时间间隔是5,即以后每隔7s输出一次结果(执行任务的时间+任务间隔)