Friday, 15 March 2013

Java Multithreading unexpected result -



Java Multithreading unexpected result -

this question has reply here:

java thread priority has no effect 9 answers

i learning multithreading in java , though measure relative cpu usage of 2 threads hi , lo on below code.

class clicker implements runnable{ long click=0; thread t; private volatile boolean running =true; public clicker(int p) { t=new thread(this); t.setpriority(p); } public void run(){ while(running){ click++; } } public void stop(){ running =false; } public void start(){ t.start(); } } public class hilopri { public static void main(string[] args) { thread.currentthread().setpriority(thread.max_priority); clicker hi = new clicker(thread.norm_priority +2); clicker lo = new clicker(thread.norm_priority -2); lo.start(); hi.start(); try{ thread.sleep(10000); }catch(interruptedexception e){ system.out.println("main thread interrupted. "); } lo.stop(); hi.stop(); try{ hi.t.join(); lo.t.join(); }catch(interruptedexception e){ system.out.println("interrupted exception caught"); } system.out.println("low priority : " + lo.click); system.out.println("high priority : " + hi.click); } }

here's outputs various priorities:

lo = norm_priority -2 , hi = norm_priority +2 : low priority : 1725664879, high priority : 1774465713 || high/low = 1.02827 lo = norm_priority -4 , hi = norm_priority +4 : low priority : 2142378792, high priority : 2180156175 || high/low = 1.01763 lo = norm_priority , hi = norm_priority : low priority : 2582216343 , high priority : 2581415280 || high/low = 0.99968

from output 3, understood in 2 threads of equal priority, first 1 gets slighly more peference.

in case of output 1 , output 2, see priority values. when priority difference became high, counts incresed. when set difference 0 (in output 3), contrary above observation, counts shows increment instead of descrease.

can explain why?

(specs : java se 7, amd a10 quad core 2.3ghz , window 8)

the java spec not guarantee priorities considered when assigning quota threads.

every thread has priority. when there competition processing resources, threads higher priority executed in preference threads lower priority. such preference not, however, guarantee highest priority thread running, , thread priorities cannot used reliably implement mutual exclusion.

java multithreading

No comments:

Post a Comment