暂停线程的三种方式:join、sleep、yield
前言
yield()
不太确定什么场合会用,遇到了再回来添加。
正文
结合 Stack OverFlow 上的《What is difference between sleep() method and yield() method of multi threading?》来进行回答。
原文如下:
We can prevent a thread from execution by using any of the 3 methods of Thread class:
- yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
- join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.
- sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).
总结一下:
1)yield()
当前正在执行的线程主动暂停,让出 CPU 给相同或更高优先级的线程,也有可能给更低的,概率问题。
(文中说让出 CPU 给相同或更高优先级的线程,但是,我看了一些文章低的也有可能)
另外,它不会释放自己持有的锁。
极少使用。
2)join()
如果线程 t1
调用 t2.join()
,则 t1
会进入等待状态,直到 t2
执行完毕。底层基于 wait()/notify()
实现。
常用于线程依赖,如主线程等待子线程完成。
3)sleep()
让当前线程休眠指定时间,并且不会释放锁。
一般用于自己练习代码使用。
sleep(0) 和 yield() 区别
Thread.sleep(0)
也是会让出当前时间片。但是 Thread.yield()
和 Thread.sleep(0)
都不能保证当前线程一定让出 CPU,其行为依赖于 JVM 实现和操作系统。不建议使用。