• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads - synchronized methods

 
janki tangeda
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Olaf Kummer
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic