devxlogo

Difference between yield() and sleep()

Difference between yield() and sleep()

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

Answer:
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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist