• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class B extends Thread{
static String s[] = new String[]{"x","y","z"};
public synchronized void run(){
System.out.println(s[0]+s[1]+s[2]);
}
public synchronized static void main(String ar[]){

new B().start();

s[0] = "A";
s[1]= "B";
s[2]="C";


}
}
i thought the answer is going to be ABC nothing else.but it is 99% printed XYZ then ABC and AYZ how come is that?
because if you synchronize the main method it should return only one output isn't it?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

because if you synchronize the main method it should return only one output isn't it?



When you synchronize on a lock, you synchronize on a lock, period. There is no magic of "one output", blah, blah, blah... Two threads must cooperate with each other. And the first requirement here is probably that they should actually synchronize on the same lock.

In this example, the new started thread has synchronized on the new instance, and the main thread has synchronized on the class lock. These are not the same lock.

Henry
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic