multithreading - Java - 4 Threads manipulate within two synchronized methods the same object data -
first of new here, hope things right during questioning.
the problem:
i have class store attribute int size;
in class 2 methods manipulate size attribute.
`public synchronized void leave(){ this.size++; }` `public synchronized void enter(){ while(this.size==0){ } this.size--; }` if initialize store object size=2;for example , 4 other objects (the 4 threads) alternately try leave() or enter()the store object endless loop. thought if write synchronized methods, leave method called thread although other thread hang in endless loop.
i hope question understandable. thank help.
first of new here, hope things right during questioning.
your question asked got @ least right :)
4 other objects (the 4 threads) alternately try leave() or enter()the store object endless loop
when 1 thread enters synchronized block, declaring no other threads can enter synchronized region of same object until thread has left initial synchronized block. have thread invoking enter , spinning until size 0. happen, size needs incremented, cannot happen because thread cannot invoke leave (while other thread spinning ever).
solution
instead of busy spinning ( while(<some condition>){ } ), have thread wait on monitor. give lock thread can enter. , after leaveing, notify waiting threads.
public synchronized void leave(){ this.size++; this.notify(); } public synchronized void enter(){ while(this.size==0){ this.wait(); } this.size--; }
Comments
Post a Comment