This is question 2 of the RHE book chapter 7(Thread), p228
2. which one statement below is always true about the following application? class HiPri extends Thread{ HiPri(){ setPriority(10); } public void run(){ System.out.println("Another thread starting up!");
while(true){} //HERE!! } public static void main(String[] args){ HiPri hp1 = new HiPri(); HiPri hp2 = new HiPri(); HiPri hp3 = new HiPri(); hp1.start(); hp2.start(); hp3.start(); } } A. When the application is run, thread hp1 will execute, threads hp2 and hp3 will never get the CPU; B. When the application is run, all three threads will get to execute, taking time-slicing turns in the CPU. C. Either A or B will be true, depending on the underlying platform. Answer given is C. =========================================================== My question is: the line while(true){} //Here!! in the run method, should we consider this an infinite loop? if so, then once any of the three hp1, hp2 or hp3 threads gets to execute, the other two will not get an chance to run. Making statement A and C incorrect but leaving B correct if time-slicing is implemented.Any response is appreciated!
Hi peter, Yes the while loop in an infinite loop. Now there are 2 approaches to scheduling threads. the approaches are 1. preemptive scheduling: there are only 2 ways a thread will leave the running state without explicitly calling the thread scheduling method such as wait() or suspend() a) when it is blocked by an I/O method b) when a higher priority thread takes over the CPU and it gets moved out. 2. time sliced scheduling - where a thread is allowed to execute for a limited time only - then others are given a chance irrespective of the priority of the thread Which implementation Java uses is dependant on the platform u r working on. eg : Solaris, windows, macintoshes etc. option A : A. When the application is run, thread hp1 will execute, threads hp2 and hp3 will never get the CPU; A will be true if the platform is one that supports preemptive scheduling. Implying that ans C is correct - that is both A & B could be true depending on the platform they are running on
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Thanks! Eskay, How can we be sure hp1 will be the first one chosen to run ? I thought there would be no guarantee for that because we have hp1, hp2, hp3 all waiting, albeit hp1 enter the runnable state first. Isn't it still possible that the thread scheduler might choose hp2 to be the first to run thus preventing hp2 and hp3 from running? Peter