• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads

 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
General rule: Don't depend on the thread scheduler for behavior.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic