Thread Control and Priorites
Thread Control and Priorites
DemoThread(String threadname) {
name = threadname;
thread = new Thread(this, name);
System.out.println("New Thread: " + thread);
thread.start();
}
• The term that is used for switching from one thread to another is
context switch
• When the thread scheduler has to pick up from several threads that are
runnable, it will check the thread priority and will decide when a particular
has to run
• The threads that have higher-priority usually get more CPU time as
compared to lower-priority threads
9 © 2009 Wipro Ltd - Confidential
Deciding on a Context Switch
• When two threads with the same priority are competing for
CPU time, threads are time-sliced in round-robin fashion in case
of Windows like OSs
• When a new Java thread is created it has the same priority as the thread
which created it
thread1.setPriority(Thread.NORM_PRIORITY + 1);
thread2.setPriority(Thread.NORM_PRIORITY -1);
thread3.setPriority(Thread.MAX_PRIORITY - 1);
thread1.start();
thread2.start();
thread3.start();
Note: Implementation of thread priority varies depending on the underlying
Operating System, and thus should never be considered as a factor when
designing application logic.
12 © 2009 Wipro Ltd - Confidential
Thread Priority - Example
To demonstrate thread priority, we will use the same demo from the ‘creating multiple threads’
topic.
Modifying the program to include thread priority: