Thread中yield()方法, join()方法- 理解记录

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

  • 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.

翻译: 提示系统调度器==当前线程==愿意放弃其正在使用的处理器资源.调度器可以忽略这个提示.(注:放弃正在使用的处理器资源也就表示一个线程将由运行状态转到就绪状态,同时也说明此线程有可能会继续被分配到处理器资源继续执行)

静态方法: 调用方式Thread.yield(); 从调用方式要理解的一个关键点是: 当前线程,那么这里的当前线程到底是哪个线程呢.比如我有代码如下:

public class TestYield {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(){
            @Override
            public void run() {
                    try {
                        System.out.println("线程执行---");
                        sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };
        System.out.println(System.currentTimeMillis());
        thread.start();
        Thread.yield();
        System.out.println(System.currentTimeMillis());
    }
}

当如上代码执行的时候, Thread.yield()执行时,是哪个线程愿意放弃正在
使用的处理器资源呢,这里是主线程.也就是说Thread.yield()在哪个线程中被调用就
表示哪个线程愿意放弃处理器资源.


join()方法

join() : 当前线程暂停执行

/**
 * Waits for this thread to die.
 *
 * <p> An invocation of this method behaves in exactly the same
 * way as the invocation
 *
 * <blockquote>
 * {@linkplain #join(long) join}{@code (0)}
 * </blockquote>
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public final void join() throws InterruptedException {
    join(0);
}

join(long millis): 当前线程暂停执行,直到millis毫秒之后继续执行

/**
 * Waits at most {@code millis} milliseconds for this thread to
 * die. A timeout of {@code 0} means to wait forever.
 *
 * <p> This implementation uses a loop of {@code this.wait} calls
 * conditioned on {@code this.isAlive}. As a thread terminates the
 * {@code this.notifyAll} method is invoked. It is recommended that
 * applications not use {@code wait}, {@code notify}, or
 * {@code notifyAll} on {@code Thread} instances.
 *
 * @param  millis
 *         the time to wait in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
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(long millis, int nanos): 当前线程执行暂停, 直到millis+namos后继续

/**
 * Waits at most {@code millis} milliseconds plus
 * {@code nanos} nanoseconds for this thread to die.
 *
 * <p> This implementation uses a loop of {@code this.wait} calls
 * conditioned on {@code this.isAlive}. As a thread terminates the
 * {@code this.notifyAll} method is invoked. It is recommended that
 * applications not use {@code wait}, {@code notify}, or
 * {@code notifyAll} on {@code Thread} instances.
 *
 * @param  millis
 *         the time to wait in milliseconds
 *
 * @param  nanos
 *         {@code 0-999999} additional nanoseconds to wait
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative, or the value
 *          of {@code nanos} is not in the range {@code 0-999999}
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public final synchronized void join(long millis, int nanos)
throws InterruptedException {

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

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }

    join(millis);
}

实例代码:

public class TestJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(){
            @Override
            public void run() {
                    try {
                        System.out.println("线程执行---");
                        sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };
        System.out.println("开始:" + System.currentTimeMillis());
        thread.start();
        thread.join(3000);
        System.out.println("结束:" + System.currentTimeMillis());
    }
}

join()是实例方法, 只能在实例级别被调用, 那么在上述例子中,当执行thread.join()
方法时, 被暂停的是主线程还是thread线程呢? 结果是主线程被暂停. 也就是说被暂停
的线程还是调用执行这句代码的线程.也就是说调用线程被暂停,而join()方法的所属
实例继续执行.如果join()方法不传参数,那么主线程会等待直到thread线程执行完毕后
才会继续执行,否则就是暂停传入时间后继续执行.
如果你想打断这种暂停, 那么你可以在thread中调用notify(),notifyAll()方法来打断.
但是就从注释中我们也可以看出并不推荐在线程实例上条用notify()或者notifyAll()方法.

补充:从源码中我们也可以看出join()方法其实是调用的Object的wait()方法来实现的,那么他又是在什么时候被notify的呢(我们知道被wait的线程必须被notify才会继续执行).从注解(==As a thread terminates the

{@code this.notifyAll} method is invoked==)可知, 当一个线程终止时,他的notifyAll()方法会被调用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 7,206评论 1 15
  • 该文章转自:http://blog.csdn.net/evankaka/article/details/44153...
    加来依蓝阅读 12,078评论 3 87
  • 写在前面的话: 这篇博客是我从这里“转载”的,为什么转载两个字加“”呢?因为这绝不是简单的复制粘贴,我花了五六个小...
    SmartSean阅读 10,249评论 12 45
  • Java多线程学习 [-] 一扩展javalangThread类 二实现javalangRunnable接口 三T...
    影驰阅读 8,100评论 1 18
  • 刚上一年级的女儿的诗 妈妈爸爸的爱。 妈妈的爱 象根藤 我象蚂蚁上面爬 爸...
    精致典雅阅读 2,578评论 0 2

友情链接更多精彩内容