aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method Synchronized 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 "Method Synchronized " Watch "Method Synchronized " New topic
Author

Method Synchronized

RAGU KANNAN
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
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

Joined: Jan 19, 2006
Posts: 584
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.


"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
RAGU KANNAN
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
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

Joined: Jan 19, 2006
Posts: 584
a.run() is working as a regular method call. such call actually does not create a new thread.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method Synchronized