当前位置: 首页 > news >正文

暂停线程的三种方式:join、sleep、yield

前言

yield() 不太确定什么场合会用,遇到了再回来添加。

正文

结合 Stack OverFlow 上的《What is difference between sleep() method and yield() method of multi threading?》来进行回答。

原文如下:

We can prevent a thread from execution by using any of the 3 methods of Thread class:

  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
  2. join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.
  3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

总结一下:

1)yield()

当前正在执行的线程主动暂停,让出 CPU 给相同或更高优先级的线程,也有可能给更低的,概率问题。

(文中说让出 CPU 给相同或更高优先级的线程,但是,我看了一些文章低的也有可能)

另外,它不会释放自己持有的锁。

极少使用。

2)join()

如果线程 t1 调用 t2.join(),则 t1 会进入等待状态,直到 t2 执行完毕。底层基于 wait()/notify() 实现。

常用于线程依赖,如主线程等待子线程完成。

3)sleep()

让当前线程休眠指定时间,并且不会释放锁。

一般用于自己练习代码使用。

sleep(0) 和 yield() 区别

Thread.sleep(0) 也是会让出当前时间片。但是 Thread.yield()Thread.sleep(0) 都不能保证当前线程一定让出 CPU,其行为依赖于 JVM 实现和操作系统。不建议使用。

http://www.xdnf.cn/news/294481.html

相关文章:

  • 教育应用场景下多智能体系统中交互模型的案例迁移
  • 大模型的监督学习和非监督学习
  • linux种文件名usr的含义是什么?
  • General Tutor 提示词延申分析
  • 11.施工监测
  • Gradio全解20——Streaming:流式传输的多媒体应用(4)——基于Groq的带自动语音检测功能的多模态Gradio应用
  • 18. 四数之和-python刷题-灵神
  • 1257: 【基础】马鞍数
  • 力扣hot100 (除自身以外数组的乘积)
  • Pinia状态管理工具速成
  • 认识并理解什么是链路层Frame-Relay(帧中继)协议以及它的作用和影响
  • 【C/C++】无锁编程——compare_exchange_strong
  • 第二章 - 软件质量
  • S100平台调试RS485/RS232
  • Python Cookbook-7.2 使用 pickle 和 cPickle 模块序列化数据
  • 【Python】 `os.getenv()` vs. `os.environ.get()`:环境变量获取方式的本质差异解析
  • Milvus(14):更改 Collections 字段、Schema 设计实践
  • (42)VTK C++开发示例 ---渲染不同颜色的20面体
  • 基于 jQuery 实现复选框全选与选中项查询功能
  • 【AI论文】KeySync:一种在高分辨率下实现无泄漏唇形同步的稳健方法
  • 开元类双端互动组件部署实战全流程教程(第1部分:环境与搭建)
  • 【自然语言处理与大模型】LlamaIndex的数据连接器和对话引擎
  • TS 函数中的类型兼容性
  • 20250505下载VLC for Android
  • 集合-探索
  • 观察者模式
  • 论文答辩讲稿脚本分享(附我自己用的版本)
  • Model Context Protocol (MCP) 技术解析
  • Kotlin中 StateFlow 或 SharedFlow 或 LiveData的区别
  • **集合**实验**