Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

15. Networking and Threads: Make a Conne... > Using sleep to make our program more...

Using sleep to make our program more predictable

Remember our earlier example that kept giving us different results each time we ran it? Look back and study the code and the sample output. Sometimes main had to wait until the new thread finished (and printed “top o’ the stack”), while other times the new thread would be sent back to runnable before it was finished, allowing the main thread to come back in and print out “back in main”. How can we fix that? Stop for a moment and answer this question: “Where can you put a sleep() call, to make sure that “back in main” always prints before “top o’ the stack”?

We’ll wait while you work out an answer (there’s more than one answer that would work).

Figure it out?

image with no caption

This is what we want–a consistent order of print statements:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint