Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronized ?  RSS feed

 
Jennifer Wallace
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jennifer Wallace
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! Its a good feeling to be able to appreciate the "synchronized" method modifier.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!