java - How threads work -
i have problem understanding how threads work:
class threadtest implements runnable{ synchronized void methoda(long n){ (int i=1;i<3;i++){system.out.print(n+" "+i)} } public void run(){ methoda(thread.currentthread.getid()); } public static void main(string ... args){ new thread(new threadtest()).start(); new thread(new threadtest()).start(); } } as understand, because methoda synchronized loop in method, must finish before next thread calls method -- result must 4-1 4-2 5-1 5-2...
is possible have result 4-1 5-1 5-2 4-2? if yes, how?
is possible have result 4-1 5-1 5-2 4-2.?
it possible.
if yes how?
you using this reference object locked synchronized. since you've got 2 distinct instances of threadtest, each method locks own instance , mutual exclusion not achieved.
so, must understand semantics of synchronized: there defined object involved monitor acquired. basically, object notes thread has acquired monitor , allow same thread re-acquire it; other threads put on hold until monitor released. other object, naturally, has nothing , monitor free acquired thread.
a synchronized method implicitly uses this lock. can example declare static final object lock = new object(); , use synchronized(lock) in method.
Comments
Post a Comment