Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Synchronized

 
RAGU KANNAN
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

The output for the following java class is Bmain OR mainB.
I would like to know why the result is unpredictable. Because this method has synchronized. So the thread run like one by one. Pls let me know why this code is not working one by one.

Thanks, Raghu.K



class MyThread extends Thread {
public void run() {
m1();
}

MyThread(String threadName) {
super(threadName);
}

public synchronized void m1() {
System.out.print(Thread.currentThread().getName());
}

public static void main(String[] args) {

MyThread a = new MyThread("A");
MyThread b = new MyThread("B");
b.start();
Thread.yield();
a.run();
}
}
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In my point of view the result is unpredictable due to following and simple reason :

Even though m1() method is marked as synchronized, it's called from two different object references. Variable (a) refers to one reference and variable (b) refers to another reference. They have distinct references because both were assigned with new keyword.
 
RAGU KANNAN
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mr.Edisandro Bessa.


I would like to know, a.run() is calling as regular method or starting a Thread?.

Thanks, Raghu.K
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a.run() is working as a regular method call. such call actually does not create a new thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic