aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads - synchronized methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads - synchronized methods" Watch "Threads - synchronized methods" New topic
Author

Threads - synchronized methods

janki tangeda
Ranch Hand

Joined: Jun 07, 2005
Posts: 54
class A extends Thread {
String[] sa;
public A(String[] sa) {this.sa = sa;}
public void run() {
synchronized (sa) {System.out.print(sa[0] + sa[1] + sa[2]);}
}}
class B {
private static String[] sa = new String[]{"X","Y","Z"};
public static void main (String[] args) {
synchronized (sa) {
Thread t1 = new A(sa); t1.start();
sa[0] = "A"; sa[1] = "B"; sa[2] = "C";
}}}

The output here is ABC and the explanation is that the t1 thread will be blocked until main method execution completes.I agree that the t1 thread is invoking a block synchronised on sa but that block is in a different class i.e class A???
Sumit David
Greenhorn

Joined: Oct 23, 2003
Posts: 10
Hi

There can be several reasons for this:

1) Arrays ar objects so they are passed by reference and they reflect any changes.

2) Thread does not start execution immediately after calling the start method.

Please tell me if I am wrong or missing out on something.


SCJP 1.4
Olaf Kummer
Greenhorn

Joined: May 02, 2005
Posts: 11
Originally posted by janki tangeda:
I agree that the t1 thread is invoking a block synchronised on sa but that block is in a different class i.e class A???


Yes, they are different classes, but they synchronize on the same object: the array that is passed into the other class. Note that this is not a synchronized method, but a synchronized(...){} statement.

Regards, Olaf
janki tangeda
Ranch Hand

Joined: Jun 07, 2005
Posts: 54
Note that this is not a synchronized method, but a synchronized(...){} statement

Why this statement?what would happen if it were a synchronized method?
Sergei Iakhnin
Ranch Hand

Joined: Nov 09, 2004
Posts: 53
Originally posted by janki tangeda:
Note that this is not a synchronized method, but a synchronized(...){} statement

Why this statement?what would happen if it were a synchronized method?


Methods are synchronized on the this object if they are non-static or on the class object if they are static while code blocks can be synchronized on any object. So if the run method was synchronized instead of the block inside the run method then t1 would only need to acquire its own lock to run whereas now it need to wait for the block inside the main method to release the lock on sa.


SCJP 1.4, SCWCD 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads - synchronized methods