aspose file tools
The moose likes Threads and Synchronization and the fly likes Synchronized ? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Synchronized ?" Watch "Synchronized ?" New topic
Author

Synchronized ?

Jennifer Wallace
Ranch Hand

Joined: Nov 30, 2001
Posts: 102
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 ?
dan moore
Ranch Hand

Joined: Nov 04, 2001
Posts: 68
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
Thanks! Its a good feeling to be able to appreciate the "synchronized" method modifier.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronized ?
 
Similar Threads
question from Dan's exam - ClassCastException
illegalaccessException
Am I wrong in understanding this MindQ qstn?
strange behavior of overridden call
one more doubt abt generics