File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Threads" Watch "Threads" New topic


Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
What is the output of this prg?

public class MyThread implements Runnable

String myString = "Yes ";

public void run()

this.myString = "No ";

public static void main(String[] args)

MyThread t = new MyThread();

new Thread(t).start();

for (int i=0; i < 10; i++)




When I run this program ,it gives yes 9times,but in one of the mock exam it gives the answer "the ouput cannot be determined."

Am i correct?
Seb Mathe
Ranch Hand

Joined: Sep 28, 2005
Posts: 225
You're right... (If you ave one "No" after your 9 "Yes", or ten "Yes")

Try to add loops (ex: i<1000)
You'll probably see "No" printed some times...

It will make more clear the assertion "the output cannot be determined".

In fact, the output can be defined by :
- A sequence of 10 words wille be printed : An indetermined number of "Yes" followed by zero or more "No".

Regards,<br />Seb<br /> <br />SCJP 1.4
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

General rule: Don't depend on the thread scheduler for behavior.
I agree. Here's the link:
subject: Threads
It's not a secret anymore!