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

Java 进阶:如何让线程主动让出 CPU

  • Java 进阶如何让线程主动让出 CPU
    • Threadsleep
    • Threadyield
    • ThreadcurrentThreadsuspend
    • Objectwait
    • LockSupportpark
    • Threadstop

Java 进阶:如何让线程主动让出 CPU

Thread.sleep

sleep 方法可以让线程主动让出 CPU,但是并不会释放锁。

/** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors. */ public static native void sleep(long millis) throws InterruptedException;

Thread.yield

yield 也可以让线程主动让出 CPU,然后和其他线程一起竞争 CPU,但是调度器也可以忽略 yield。哪些情况会用到 yield 呢?
1. 一般在 debug 和 test 中使用。
2. CPU 密集型应用主动让出 CPU 以避免过度占用 CPU,影响其他任务。

/** * A hint to the scheduler that the current thread is willing to yield * its current use of a processor. The scheduler is free to ignore this * hint. * * <p> Yield is a heuristic attempt to improve relative progression * between threads that would otherwise over-utilise a CPU. Its use * should be combined with detailed profiling and benchmarking to * ensure that it actually has the desired effect. * * <p> It is rarely appropriate to use this method. It may be useful * for debugging or testing purposes, where it may help to reproduce * bugs due to race conditions. It may also be useful when designing * concurrency control constructs such as the ones in the * {@link java.util.concurrent.locks} package. */ public static native void yield();

Thread.currentThread().suspend()

该方法已过时。为啥呢?suspend 挂起线程,并不会释放锁,又不像 sleep 那样一段时间后自动恢复,所以容易引起死锁。相对应的 resume 方法用于唤醒一个 suspend 的线程。

/** * Suspends this thread. * <p> * First, the <code>checkAccess</code> method of this thread is called * with no arguments. This may result in throwing a * <code>SecurityException </code>(in the current thread). * <p> * If the thread is alive, it is suspended and makes no further * progress unless and until it is resumed. * * @exception SecurityException if the current thread cannot modify * this thread. * @see #checkAccess * @deprecated This method has been deprecated, as it is * inherently deadlock-prone. If the target thread holds a lock on the * monitor protecting a critical system resource when it is suspended, no * thread can access this resource until the target thread is resumed. If * the thread that would resume the target thread attempts to lock this * monitor prior to calling <code>resume</code>, deadlock results. Such * deadlocks typically manifest themselves as "frozen" processes. * For more information, see * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. */ @Deprecated public final void suspend() { checkAccess(); suspend0(); } @Deprecated public final void resume() { checkAccess(); resume0(); }

Object.wait

wait 会把当前持有的锁释放掉同时阻塞住,让出 CPU。当其他线程调用 Object.notify/notifyAll 时,会被唤醒,可能得到 CPU,并且获得锁。

LockSupport.park

这就是锁了嘛,相对应的用 unpark 解锁。

Thread.stop

该方法已过时,直接停止线程,同时会释放所有锁,太过暴力,容易导致数据不一致。

http://www.cnnetsun.cn/news/485096.html

相关文章:

  • HDFS的架构优势与基本操作
  • 通信协议仿真:蓝牙协议仿真_(8).蓝牙仿真硬件平台
  • 基于 VSC 的 UPFC(统一潮流控制器)研究(Simulink)
  • jQuery 语法详解
  • BO-LSTM贝叶斯优化长短期记忆神经网络回归预测(多输入单输出)MATLAB代码
  • HeidiSQL导入与导出数据
  • 《AI元人文构想:风骨智能体的舞台实践》深度研究报告
  • 学长亲荐10个一键生成论文工具,专科生轻松搞定毕业论文!
  • python_flask求职招聘岗位信息分析系统的设计与实现_xz0yin70可视化大屏
  • python_flask重庆旅游推荐系统_4ojn0or1爬虫可视化
  • 【江湖科技公司】一文带你了解上门按摩系统软件公司怎么选
  • golang debug调试
  • 深度学习计算机毕设之基于python的玉米粒品质检测基于深度学习的玉米粒品质检测
  • 神州信息×陕西农信:AI驱动数据资产管理,打造数字金融创新案例
  • GO和kEGG富集分析
  • AI大模型对就业的影响——典型岗位盘点,非常详细收藏我这一篇就够了
  • Failed to restart nginx.service Unit nginx.service not found
  • error @achrinzanode-ipc@9.2.5 The engine “node“ is incompatible with this module. 解决node.js版本不兼容问题
  • ERROR 1524 (HY000) Plugin ‘mysql_native_password‘ is not loaded
  • 代码随想录刷题——二叉树篇(十二)
  • DeepSeek R1 简易指南:架构、本地部署和硬件要求
  • 终极降AI指南!这款能让你相见恨晚的论文降aigc神器,实测降ai效果立竿见影
  • 还在为AI率爆表发愁吗?这几款降ai率工具推荐,实测免费降低ai率只需三步,建议反复观看!
  • Flutter 持续数据流设计:为什么一定要用 BasicMessageChannel?
  • AI驱动的企业财务舞弊模式演化跟踪系统
  • CES 2026最酷笔记本电脑:可拆卸设计成为新趋势
  • CentOS7安装Mysql5.7(ARM64架构)
  • 80-02210-001 PCB模块
  • 7D-AI系列:Vibe Coding VS Spec Coding AI 编程的两种范式对比
  • 基于Python+Django的框架的青岛开发区芳华美容院管理系统毕设源码+文档+讲解视频