Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Method Synchronized

 
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();
}
}
 
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.
 
Cob is sand, clay and sometimes straw. This tiny ad is made of cob:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic