java - Why don't these threads run in sequence? -
this question has answer here:
- synchronized block not working 8 answers
i have difficulty understanding synchronized
, reentrant lock. here small program experimenting with:
import java.util.concurrent.executorservice; import java.util.concurrent.executors; public class reentr { public static void main(string[] args) { executorservice eservice = executors.newfixedthreadpool(2); (int = 1; <= 2; i++) { eservice.execute(new process()); } try { thread.sleep(1); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } eservice.shutdown(); } } class process implements runnable { int count = 0; @override public void run() { processtest(); } public synchronized void processtest() { try { (int = 1; <= 2; i++) { count += i; system.out.println("count value " + thread.currentthread().getname() + " " + count); } } { system.out.println("count " + thread.currentthread().getname() + " " + count); } } }
the output was:
count value pool-1-thread-2 1 count value pool-1-thread-1 1 count value pool-1-thread-2 3 count pool-1-thread-2 3 count value pool-1-thread-1 3 count pool-1-thread-1 3
if see in output 2 thread in synchronized block. under impression 1 thread has complete execution of synchronized method, after other thread enter method.
ideally, expecting result this
count value pool-1-thread-1 1 count value pool-1-thread-1 3 count pool-1-thread-1 3 count value pool-1-thread-2 1 count value pool-1-thread-2 3 count pool-1-thread-2 3
i have replaced synchronized method synchronized block , re-entrant locks. however, still have same output. missing?
the 2 threads not synchonizing on same object.
you have 2 different instances of process
(as aside; should name classes capital letter). synchronized
keyword equivalent to:
public void processtest() { synchronized(this) { // etc.. } }
if want 1 thread run after other, must synchronize on same object. if did this, example:
class process implements runnable { // note static private static final object lock = new object(); public void processtest() { synchronized(lock) { // code } } }
then code have 1 thread run after other. way pass lock object
s constructor, or same instance of semaphore
, etc.
Comments
Post a Comment