Two Laptop Bag*
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
Author

Thread synchonization

gunjan deogam
Greenhorn

Joined: Aug 02, 2009
Posts: 11

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.


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
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

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.


Steve
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Thread synchonization
 
Similar Threads
Threads question.
Using non-static object as lock in Threads PRoblem
Question on multithreading from Sierra/Bates Chapter 9, Question 16
Thread.yield()
Doubt in Threads