02-Thread--基础线程机制

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值