Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

New to Java - Synchronization  RSS feed

 
John O' Donovan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am currently studying for the Java exam and am writing some code to test the Synchronization keyword.
Here is the code



the output i'm seeing is this

run:
About to call t1 Fri Jun 12 11:34:51 BST 2009
About to call t2 Fri Jun 12 11:34:51 BST 2009
t1 starting at Fri Jun 12 11:34:51 BST 2009
t2 starting at Fri Jun 12 11:34:51 BST 2009
t1 in while loop
t2 in while loop
t2 finished at Fri Jun 12 11:34:51 BST 2009
t1 finished at Fri Jun 12 11:34:51 BST 2009

From what I understand about the synchronization keyword, shouldn't t2 block until t1 is finished.

From Sun
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Sun Thread Tutorial

there's probable something i'm missing but if someone could help i'd appreciate it.

 
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
there's probable something i'm missing but if someone could help i'd appreciate it.


The missing item is here...

From Sun
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.


The synchronized run() methods are executed using two different ThreadClass objects -- ie. they are not the same object.

Henry
 
John O' Donovan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's it, thanks very much.

John
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!