Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread synchonization

 
gunjan deogam
Greenhorn
Posts: 11
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • 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.
 
Himanshu Kansal
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • 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".
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • 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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic