I am trying to understand synchronization and just tried to code a simple program . But the output is not what I expected. Cud some body explain? public class sub extends Thread{ public static void main(String[] args) { sub sub1=new sub(); sub1.setName("Sub1"); sub1.start(); sub sub2=new sub(); sub2.setName("Sub2"); sub2.start(); } synchronized public void run() { String str=getName(); for(int i=0;i<10;i++) System.out.println(str); } } I wud expect sub1 to print 10 times and then sub2 10 times. But there is a overlap between the two sometimes. Why is it so ?
synchronization works on a per-instance basis. synchronized method means that the first thread will obtain a lock on the sub1 instance, the second thread on the sub2 instance. this code may provide what you are looking for:
now the threads will both be synchronised on singleSub, so one thread will need to return from run() and release the lock before the other enters. undefined as to which runs first methinks. or maybe it is just Java vengeance for your non-standard class capitalisation. cheers, dan.
dan moore, infomatiq ltd.<br />email dan@infomatiq.co.uk<br /><a href="http://www.infomatiq.co.uk" target="_blank" rel="nofollow">http://www.infomatiq.co.uk</a>
Jennifer Wallace
Ranch Hand
Joined: Nov 30, 2001
Posts: 102
posted
0
Thanks! Its a good feeling to be able to appreciate the "synchronized" method modifier.