multithreading - java synchronize multiple thread issue -
i write code test multiple threads how synchronize,but cannot expected result.the code can start 3 threads,but 1 thread process shared resource.what wrong code.
class threaddemo1{ public static void main (string[] args){ multithread tt = new multithread(); new thread(tt).start(); new thread(tt).start(); new thread(tt).start(); } } class multithread implements runnable { int tickets = 100; object _lock = new object(); public void run () { system.out.println(thread.currentthread().getname()); synchronized(_lock) { while (true) { if (tickets>0) { try { thread.sleep(10); } catch (exception e) {} system.out.println(thread.currentthread().getname() + " selling "+tickets--); } } } } }
you sleeping while holding lock. there no reason multithread if going that.
public void run () { system.out.println(thread.currentthread().getname()); while(tickets > 0) { synchronized(_lock) { if (tickets > 0) { system.out.println(thread.currentthread().getname() + " selling " + tickets--); } } try { thread.sleep(10); } catch (exception e) { } } } i'm guessing sleep placeholder processing. if possible, should check , decrement inside synchronized block, lengthy processing outside it.
in order locks , multi-threading useful you, must make sure synchronized code takes little time possible, since code can run 1 thread @ time.
in code, thing wasn't single-threaded first system.println.
fyi, in mind, if have print statements accurate possibly out of order, better have:
public void run () { system.out.println(thread.currentthread().getname()); while(tickets > 0) { int oldtickets = 0; synchronized(_lock) { if (tickets > 0) { oldtickets = tickets--; } } if(oldtickets > 0) { system.out.println(thread.currentthread().getname() + " selling " + oldtickets); try { thread.sleep(10); } catch (interruptedexception e) { } } } }
Comments
Post a Comment