Two Laptop Bag*
The moose likes Threads and Synchronization and the fly likes Threads example problems?? 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 » Threads and Synchronization
Bookmark "Threads example problems??" Watch "Threads example problems??" New topic
Author

Threads example problems??

Roshini Chandrasekar
Greenhorn

Joined: Sep 24, 2007
Posts: 6
Guys can anybody please reply to this: I am so confused.

1). Assume that integer x is initially 0 and Thread 1--> x=1; Thread 2--> x=2; and thread 3--> y=x;

Now whats the value of y? and how would you code this into a Program?

Waiting for reply.
Thanks
Roshini Chandrasekar
Greenhorn

Joined: Sep 24, 2007
Posts: 6
I am a beginner to java completely. Soo please don't think any bad if this is real silly. I am thinking the answer would be y=2. Is it correct??

Thanks.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40

Originally posted by Roshini Chandrasekar:
I am a beginner to java completely. Soo please don't think any bad if this is real silly. I am thinking the answer would be y=2. Is it correct??

Thanks.


It can actually be 0, 1, or 2. If thread 1 writes and then thread 3 reads, then it will be 1. If thread 2 writes and then thread 3 reads, then it will be 2. If thread 3 reads before either thread 1 or 2 gets to it, then it will be 0. (The caches will also have an affect on the outcome too)

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
It can actually be 0, 1, or 2.

Ah, the glory of running threads! It's just part of the deal that you can't know ahead of time in what order different threads will do things. You can go to a lot of effort to force them into some sequence, but if you want sequential operations, you probably don't want threads.

Do you have a real business problem to solve, or is "We cannot know" a valid answer to a quiz? If it's a real situation, let's dig into more details and see if we can help.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Roshini Chandrasekar
Greenhorn

Joined: Sep 24, 2007
Posts: 6
Thanks Henry and Stan.. Guess what I thought is correct It's not about real time application actually.. Just started threads in java and going through some example problems.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads example problems??
 
Similar Threads
int c=1; c=c++; // c is then 1 not 2 !
Help needed with the Code
local final variable
scjp chapter 5 q...5 page no 303