• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Thread synchonization

 
Greenhorn
Posts: 11
Netbeans IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Chicks {
synchronized void yack(long id) {
for(int x = 1; x < 3; x++) {
System.out.println(id + " ");
Thread.yield();
}
}
}

public class ChicksYack implements Runnable {
Chicks c;
public static void main(String args[]){
new ChicksYack().go();
}
void go() {
c = new Chicks();
new Thread(new ChicksYack()).start();
new Thread(new ChicksYack()).start();
}

public void run() {
c.yack(Thread.currentThread().getId());
}
}

please tell me anyone the output of above code, and explain why.
 
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[code] tags please.

While starting your threads with "new Thread(..)" you are passing anonymous objects, and "Thread.current.." doesn't know what to refer to so returns a NPE. replace "new ChicksYack()) by "this" and see it working.

Also the threads start for an anonymous object -> new ChicksYack().go()

Java is a short term memory loss patient. It needs references to remember objects. When you can't do that, use "this".
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wanted to repeat Himanshu's suggestion of using code tags. You can use code tags like this:
[code]
... your code here ...
[/code]

Or you can use the Code button at the top of the new message form to insert them.


gunjan deogam wrote:please tell me anyone the output of above code, and explain why.



Regarding this type of question. To best way to get the output for code is to run the code and see what you get. Then if you don't understand it, then tell us what the output is and what part you don't understand.

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic