java - Understanding threads and synchronization on a class that spawns the thread -
ok, can 1 explain me gap in knowledge here?
initially example below trying synchronize instance method, realised spawn new instance , therefore lock wouldn't happen.
so decided make lock on static method of class in hope thread run in order still no luck. can explain error of ways? ( bear me there better ways getting understanding right, i'm php developer going java, love - i'm 2 days in ;-) )
so @ time numbers print out in random order.
class 1
package learningjava; public class learningjava { /** * @param args command line arguments */ public static void main(string[] args) { threadcaller ob1 = new threadcaller("this test string 1"); threadcaller ob2 = new threadcaller("this test string 2"); threadcaller ob3 = new threadcaller("this test string 3"); threadcaller ob4 = new threadcaller("this test string 4"); threadcaller ob5 = new threadcaller("this test string 5"); try { ob1.t.join(); ob2.t.join(); ob3.t.join(); ob4.t.join(); ob5.t.join(); } catch (interruptedexception e) { system.out.println(e); } } }
class 2
package learningjava; public class threadcaller implements runnable { private string message; public thread t; public threadcaller(string text) { message = text; t = new thread(this); t.start(); } public static synchronized void echo(string message) { system.out.println(message); } public void run() { threadcaller.echo(this.message); } }
can explain error of ways?
basically, you're expecting ordering isn't guaranteed. you're calling start()
on lots of threads in succession... there's no guarantee 1 start executing first. fact you've got static synchronized method means 1 thread executing method @ time - doesn't guarantee ordering.
imagine have running track one-lane gate 100m down track. start race - runner reach gate first?
fortunately, isn't problem - if it's worth starting multiple threads something, usually don't care order in execute. if do, it's time re-examine design.
Comments
Post a Comment