Thread.sleep


Thread.sleep()

  1. The current thread changes state from Running to Waiting/Blocked as shown in the diagram below.
  2. Any other thread with reference to the thread currently sleeping (say t) can interrupt it calling t.interrupt()
    • the call to sleep has to be encapsulated to catch the checked exception of InterruptedException
  3. After the time period for which the thread was set to sleep it goes to the Runnable state andmight not run immediately! It has to wait for the Thread Scheduler to schedule it for its time slice.

Thread.yield()

  1. Calling it may cause the Thread Scheduler to move the current thread from Running toRunnable state and execute another same priority thread which was in Runnable state. This transition of state takes place only if there is some other thread of same priority in Runnable state. Hence the no guarantee that the thread will stop execution as the criteria of another same priority thread might not be met.
  2. .yield() is much based on the Thread Priorities concept. (All thread are assigned priorities and when a thread of higher priority is in Runnable state it ususally preempts / stops execution of lower priority threads depending on implementation of ThreadScheduler.)

enter image description hereNote:

  • both Thread.sleep() and Thread.yield() are static functions and affect the current thread executing it.
  • both the functions will not let go the synchronized locks they hold.

转载于:https://www.cnblogs.com/yunxiblog/p/5215668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值