This week's book giveaway is in the OCAJP forum.We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

Roshini Chandrasekar
Greenhorn
Posts: 6

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?

Thanks

Roshini Chandrasekar
Greenhorn
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
Marshal
Posts: 21367
84
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

Stan James
(instanceof Sidekick)
Ranch Hand
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.

Roshini Chandrasekar
Greenhorn
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.