• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads example problems??

 
Roshini Chandrasekar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21489
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic