• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
Ranch Hand
Posts: 657
Spring VI Editor Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
General rule: Don't depend on the thread scheduler for behavior.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic