• 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

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

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

更多推荐

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