File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Doubt" Watch "Thread Doubt" New topic

Thread Doubt

NDP Prasad
Ranch Hand

Joined: Apr 13, 2006
Posts: 177
public class newqw implements Runnable {
public static void main(String[] args) {
new Thread(new newqw("Wallace")).start() ;
new Thread(new newqw("Gromit")).start();
private String name;
public newqw(String name) { = name; }
public void run() {
private synchronized void message(int n) {
System.out.print(name + "-" + n + " ");

why is the above code printing different answers at different times? what should i do to get a same answer always?

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243


why is the above code printing different answers at different times? what should i do to get a same answer always?

Dismantle your system and change your processor. Just kidding. This is what expected regarding the behaviour of thread. Thereads dont run the way you like, it is totally under the control of the JVM. You don't have to worry about this.

Jothi Shankar Kumar. S

SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
catherine powell

Joined: Oct 07, 2006
Posts: 26

I believe the problem is that you created a new Runnable object for each thread and you're using these different objects for synchronization. Since each thread is looking to obtain a different object lock (each thread is looking to obtain it's own Runnable object's lock) none of them will encounter a situation where they are blocked and cannot obtain the lock they're looking for, so really there's no sychronization.

I think one possible solution would be to create a static reference variable in the Runnable class (so just 1 lock is available) and sychronize the code in your run method on that (see below).

I agree. Here's the link:
subject: Thread Doubt
Similar Threads
answer of this code
Problem with Chapter 9 Question 1
please Explain This question
thread doubt
Question about threads in Kathy's Book.I don't understand.