wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Threads" Watch "Threads" New topic
Author

Threads

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++)

System.out.print(t.myString);

}

}

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: http://aspose.com/file-tools
 
subject: Threads
 
Similar Threads
run() method
a question about thread.
THREAD QUESTION OF K&B!! confused
java.lang package is not importing by default
Aaargh! Still Weak on Threads