码迷,mamicode.com
首页 > 其他好文 > 详细

Thread.sleep( ) vs Thread.yield( )

时间:2016-02-25 07:55:26      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:


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

技术分享Note:

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

Thread.sleep( ) vs Thread.yield( )

标签:

原文地址:http://www.cnblogs.com/yunxiblog/p/5215670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!