Meaningless Drivel is fun!
The moose likes Threads and Synchronization and the fly likes Thread synchonization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread synchonization" Watch "Thread synchonization" New topic

Thread synchonization

gunjan deogam

Joined: Aug 02, 2009
Posts: 11

class Chicks {
synchronized void yack(long id) {
for(int x = 1; x < 3; x++) {
System.out.println(id + " ");

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() {

please tell me anyone the output of above code, and explain why.

Gunjan Deogam SCJP6, SCWCD5
Himanshu Kansal
Ranch Hand

Joined: Jul 05, 2009
Posts: 257
[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".

Experience and talent are independent of age
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

I wanted to repeat Himanshu's suggestion of using code tags. You can use code tags like this:
... your code here ...

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.

I agree. Here's the link:
subject: Thread synchonization
It's not a secret anymore!