Executor
Executor 管理者线程的生命周期,提供了多个方法供我们使用。
Executor的继承体系
ThreadPoolExecutor实现的顶层接口是Executor,顶层接口Executor提供了一种思想:将任务提交和任务执行进行解耦。用户无需关注如何创建线程,如何调度线程来执行任务,用户只需提供Runnable对象,将任务的运行逻辑提交到执行器(Executor)中,由Executor框架完成线程的调配和任务的执行部分。ExecutorService接口增加了一些能力:(1)扩充执行任务的能力,补充可以为一个或一批异步任务生成Future的方法;(2)提供了管控线程池的方法,比如停止线程池的运行。AbstractExecutorService则是上层的抽象类,将执行任务的流程串联了起来,保证下层的实现只需关注一个执行任务的方法即可。最下层的实现类ThreadPoolExecutor实现最复杂的运行部分,ThreadPoolExecutor将会一方面维护自身的生命周期,另一方面同时管理线程和任务,使两者良好的结合从而执行并行任务。
摘自:https://tech.meituan.com/2020/04/02/java-pooling-pratice-in-meituan.html
守护线程 Daemo
阅读材料:https://blog.csdn.net/shimiso/article/details/8964414
当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程。
main() 属于非守护线程。
在线程启动之前使用 setDaemon() 方法可以将一个线程设置为守护线程。
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}
wait , sleep , yield
阅读素材一: https://javarevisited.blogspot.com/2011/12/difference-between-wait-sleep-yield.html#axzz6n07ehEDk
This difference is more obvious from the fact that, when a thread calls the wait() method, it releases the monitor or lock it was holding on that object, but when a thread calls the sleep() method, it never releases the monitor even if it is holding.
Coming back to yield(), it’s little different than wait() and sleep(), it just releases the CPU hold by Thread to give another thread an opportunity to run though it’s not guaranteed who will get the CPU.
阅读素材二:https://www.cnblogs.com/aspirant/p/8876670.html
wait(): when a thread calls the wait() method, it releases the monitor or lock it was holding on that object
sleep(): when a thread calls the sleep() method, it never releases the monitor even if it is holding.
yeild(): it just releases the CPU hold by Thread to give another thread an opportunity to run though it’s not guaranteed who will get the CPU.