美文网首页
thread join与yield

thread join与yield

作者: 吃花生的小猴子 | 来源:发表于2017-12-05 11:32 被阅读0次

yield

    /**
     * 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();

yield:英文意思是:屈服,退让。在线程中也有类似意思,意思是当前线程退让出使用权,把运行机会交给线程池中拥有相同优先级的线程。线程调用了yield方法,该线程就从运行状态变为可运行状态

join

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

join 底层还是运用wait,所以join的作用是谁调用,谁等待。比如:

      Thread a = new Thread(() ->{
            System.out.println("this is a");
       });

        a.start();

        a.join();

        System.out.println("this is main thread");

结果:
this is a
this is main thread

调用a.join()的是主线程,相当于主线程调用了wait方法,所以主线程等待a线程执行完了再执行。

相关文章

网友评论

      本文标题:thread join与yield

      本文链接:https://www.haomeiwen.com/subject/rewqixtx.html