"Let's continue our lesson. What are thread priorities and why are they needed?
"In real world problems, the importance of the work being performed by different threads can vary greatly. The concept of thread priority was created to control this process. Each thread has a priority represented by a number from 1 to 10."
"10 is the highest priority."
"1 is the lowest."
"If no priority is given, then a thread get priority 5 (normal)."
A thread's priority does not significantly affect its work, but instead is more of a recommendation. If there are several sleeping threads that need to run, the Java machine will start a thread with a higher priority first.
"The Java machine manages threads as it sees fit. Threads with low priority won't be left to idle. They will simply receive less execution time than others, but they'll still be executed."
"In most cases, threads are always executed with the same priority. An attempt to give one thread more than others is often an indication of architectural problems in a program."
"Whoa. And I had already dreamed of assigning the highest priority to my threads so they would do 10 times as much."
"It turns out that the situation here is close to finalize: a thread with a high priority can and will work more, but maybe not—there is no guarantee."
"Say, how do I change the priority of a thread?"
"It's very easy. The Thread class has two methods:"
|Sets a new priority|
|Returns the current thread priority|
"The Thread class also has three constants:"
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
"Let me guess. MIN_PRIORITY is the minimum priority, MAX_PRIORITY is the maximum, and NORM_PRIORITY is the default priority?"
"Yes, exactly. You can write the code that assigns the highest thread priority."
"Is there some trick here? Something like this?"
Thread thread = new MyThread(); thread.setPriority(Thread. MAX_PRIORITY) thread.start();
"That’s correct. Nothing complicated, right?"
"Yep. Can you set/change the priority after a thread starts? Or is it like setDaemon, where you have to set the value before the thread is started?"
"The priority can be changed after a thread is started. As I already said, this doesn't result in any dramatic changes."
"Well, that was a small but interesting topic. Thanks, Ellie."
GO TO FULL VERSION