What is the difference between calling
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
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
sleep(t) where t is an integer.
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.
Thread.setPriority to learn and modify a thread’s prioritiy.