This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Output from synchronization ....  RSS feed

 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sir...
This is Naseem here. I have one confusion in synchronization concept.
I read that in synchronization if one thread is accessing ny synchronized method, no other thread can access that method at that time. I am getting that same from my code.

In main method I created 100 different threads.
Now in threads's run() method i hav a synchronized method test() which just print int value from 0 to 9.

public void run(){test();}

public synchronized void test(){
for(int k=0;k<=9;k++){
System.out.print(k);
}
System.out.print("");
}

In one run its output coming is
0123456789
01234567890000000000111111111122222222223333333333444444444455555555566666666567
777777677888888788999999899.....etc

Since test method is synchronized, so only one thread must enter in test method at a time so what I think is the output should come like this:
First thread prints : 0123456789
Second thread prints: 0123456789
Third thread prints : 0123456789
Fourth thread prints: 0123456789
.
.
etc.(Total 100 value for 100 thread)

means in every SOP value should be 0123456789.

Plz help...

Thanks & Regards

Naseem Khan
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that in synchronization if one thread is accessing ny synchronized method, no other thread can access that method at that time. I am getting that same from my code.


Close, but not completely true. For static methods, if one thread is accessing a synchronized static method, no other thread can access any synchronized static method, of that class, at that time. For non-static methods, if one thread is accessing a synchronized method, no other thread can access any synchronized method, of that *instance* of the class, at the same time.

In your case, I am willing to bet that each of the 100 threads are working with a different instance.

Henry
[ January 02, 2006: Message edited by: Henry Wong ]
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK. I got it. Tx for your reply. I run the same logic which u just told and it worked as expected. Thanks once again :-)

Bye

Naseem Khan
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!