Thread 中join方法 和 yield()

本文详细介绍了Java中线程的join与yield方法。join方法用于等待一个线程结束,有三种重载形式,包括无限期等待和指定时间等待。而yield方法则是一个提示性的方法,用于建议当前线程放弃处理器使用权,但不保证一定会被调度器采纳。

join 有三个重载方法
源码中的介绍:英文不太好,翻译的不知道可口不

public final void join() throws InterruptedException
// Waits for this thread to die.
表示等待该线程的终止

public final void join(long millis) throws InterruptedException
// Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
等待该线程终止的时间最长为 millis 毫秒。超时如果为 0 线程要一直等下去。

public final void join(long millis,int nanos) throws InterruptedException
* Waits at most {@code millis} milliseconds plus
* {@code nanos} nanoseconds for this thread to die.
等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。

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.
 */

为了防止一些线程独占CPU资源(这样其它的线程就得不到”响应”了).
可以让当前执行的线程”休息”一下.但是这种thread.yield() 调用,
并不保证下一个运行的线程就一定不是该线程.
可以考虑用Thread.sleep(long millis);
方法强制当前线程睡眠至少millis毫秒.

但是使用时要对该方法捕获.
调用方法很简单,只要在要睡眠的线程中加入
Thread.yield();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值