Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 28, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Difference between yield() and sleep()

What is the difference between calling yield() and sleep()? Also, in what instances would you call either method?

The Java platform uses the multithreading facilities of the host OS to implement multithreading.

There are two flavors of multithreading facilities: preemtive and non-preemptive. In a non-preemptive system all runnable threads wait in a ready queue for the currently running thread to release the CPU. This happens either because the thread terminates, requests I/O, or calls suspend(), wait(), sleep(t), yield() or stop().

In a preemptive system, the CPU is allocated to a thread for a time slice (e.g. one second). If a thread doesn't release the CPU before its time slice expires, it will be interrupted, sent back to the ready queue, and the CPU will be allocated to the "next" thread waiting in the ready queue.

Most host multithreading systems are preemptive, but some are not (e.g. Solaris' "Green Threads"). This means multithreaded Java programs can exhibit platform-dependent behavior. One way to mitigate this problem is to write COOPERATIVE THREADS. A thread is cooperative if it occasionally releases the CPU specifically so other threads can run. There are two ways to do this: by calling yield() or sleep(t) where t is an integer.

Calling sleep(t) causes the thread to suspend itself for at least t milliseconds. Calling yield() causes the thread to rejoin the ready queue.

Warning: The Java ready queue is a priority queue. This means threads are inserted according to their priority. The maximum priority of a Java thread is 10. The minimum priority is 1, and the normal priority is 5. A thread with priority n is inserted into the ready queue ahead of all threads with priority < n, but behind all threads with priority >= n. Hence, if a co-operative thread with priority n calls yield(), this only means ready threads with priority >= n will get a chance to run.

Use Thread.getPriority and Thread.setPriority to learn and modify a thread's prioritiy.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date