Thread priorities, synchronization and messaging
by, 11-13-2011 at 11:47 AM (2747 Views)
I assume that you have the basic knowledge of threads. In this post, I will write about thread priorities, synchronization and messaging.
In multithreading environment, one thread might require the attention of the CPU more quickly than other. In such a case that thread is said to be of high priority. Priority of a thread determines the switching from one thread to another. In other words, priority determines how a thread should behave with respect to the other threads.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
∑ The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
∑ All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
The word priority should not be confused with the faster running of a thread. A high priority thread does not run any faster than the low priority thread. A thread can voluntarily leave the control by explicitly stopping, sleeping or blocking on pending I/O or it can pre-empted by the system to do so. In the first case the processor examines all threads and assigns the control to the thread having the highest priority. In the second case, a low priority thread that is not ready to leave the control is simply pre-empted by the higher priority thread no matter what it is doing. This is known as pre-emptive multi-tasking. It is advisable that in case two threads have the same priority, they must explicitly surrender the control to their peers.
Multithreading produces asynchronous behavior among the programs. This means that all threads run as independent units without affecting each other. But sometimes it becomes necessary to synchronize these threads. For example, synchronization must be provided when two threads share the same variable or data structure like an array. In such a case there must be way by which they should not come in each otherís way.
Since there are more than one thread in a multithreaded environment, inter-process communication becomes imperative. A thread should be able to communicate with the other threads. Threads can talk to each other by using method such as wait().