The difference between sleep() and yield() of Thread in java, and the difference between yield() and join()

sleep() and yield()
1. When the sleep() method gives other threads a chance to run, the priority of the thread is not considered. Therefore, after the high-priority thread sleep(), the low-priority task has the opportunity to run; but yield( ) Will only give the same priority or a higher priority thread a chance to run, or even continue to run by itself

2. After the thread calls sleep(), it turns into a blocking state, and after calling yield(), it turns into a ready state.

3. The sleep method declares to throw InterruptedException, which will be caught in run() because the exception cannot be propagated back to main across threads. And the yield did not declare any exception

4.sleep() method has better portability than yield()

5: Java SE5 introduces a more explicit version of sleep(). As part of the TimeUnit class, you can specify the delay time unit through the TimeUnit.MILLISECONDS.sleep(int) method.

The function of yield() and join()
join() is to let the "main thread" wait for the end of the "child thread" before continuing

The function of the yield() method is to suspend the currently executing thread object and let other threads of the same priority execute. It is a static method and only guarantees that the current thread gives up the CPU, and does not guarantee that other threads will occupy the CPU. The thread that executes yield() may be executed again immediately after entering the suspended state

Guess you like

Origin blog.csdn.net/weixin_43916777/article/details/104187290