Java 线程的sleep和yield方法

本文介绍了Java中的线程调度机制,包括yield方法如何让出当前线程执行机会给相同优先级的线程,以及sleep方法如何使当前线程暂停指定的时间长度,让出CPU资源给其他线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute.

yield方法临时停止当前线程的执行,给其他的和当前线程同样优先级的线程一个执行的机会。

If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. 

如果在调度池中没有等待的线程或者所有等待的线程的优先级没有调用yield线程的优先级高,当前线程继续执行。

The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

什么时候执行已经yield的线程是由线程调度器来决定的,这和JVM的实现有关。


sleep() causes the current thread to suspend execution for a specified period. 

sleep方法使得当前执行的程序停止一段时间,这时线程会让出CPU来给其它的线程。

This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. 

这样可以使得同一个程序的线程或者别的程序有CPU时间来执行自己。

The sleep method can also be used for pacing and waiting for another thread with duties that are understood to have time requirement.

sleep方法也可以用来等待其它线程,但是有时间限制罢了。

sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.

sleep方法有两个重载的方法,一个用毫秒作为参数,另外一个用毫秒和纳秒作为参数。


    sleep(long millis)
    sleep(long millis,int nanos)

http://www.tkhts.com/core-java/multithreading/java-thread-scheduler.jsp


PS:

Java Thread Scheduler
The JVM is based on Preemptive and priority based scheduling algorithm.

The thread with more priority is given first preference than the thread with less priority.

The thread with more priority relinquishes (empties) the thread with less priority that is being executed.  ?

If the threads of equal priority are in the pool, the waiting time is taken in consideration.

Nature of threads sometimes affects. The daemon threads are given less importance and are executed only when no other thread is available for execution.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值