• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Scheduling(Please help)  RSS feed

 
sandeep bagati
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have got two threads two threads in my program.One of the threads is printing two variables
say integers i and j(System.out.println(i+""+j))

Is there a possibility that while i is printed j is not because of the start of other thread ???I think both will be printed.Other thread is changing the value of i and j;
Thanks sandeep
[This message has been edited by sandeep bagati (edited March 17, 2001).]
 
khudiram Barik
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please describe your problem with more detail ? What and how are you trying to achieve ?
If at all you want to share the variables values between threads spanned from the same place(class) then you can do in two ways
1. synchronize the variables access
2. declare them as volatile
 
Rahul Rathore
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both, values of i and j will be accessed but if the current thread is not synchronizing with updater thread on the SAME object, then it is not guaranteed that values of i/j will be pre-update or post update- for eg. it is possible that value of i may be its pre-update value and value of j may be post-update value.

[This message has been edited by Rahul Rathore (edited May 06, 2001).]
 
tom Su
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
println(i+j) will print out only one number = i+j,
println(""+i+j) will print out both i and j as if they were two Strings.
println(i+"'+j) may five you a comilation error at front. or runtimeerror
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sandeep bagati:
Is there a possibility that while i is printed j is not because of the start of other thread ???

No, but that's simply because i and j are not printed separately anyway! What your statement "System.out.println(i+""+j)" does is first concatenate the String representations of i and j and then print the concatenated string.
But, to rephrase Rahul's point, a thread may be interrupted for the execution of another thread at any arbitrary point. This applies to the Java library as well as to your own applications. So it is very well possible that your statement has concatenated i with "", then gets interrupted by the other Thread, and finishes the concatenation with j after the other Thread has updated it.
- Peter

[This message has been edited by Peter den Haan (edited May 05, 2001).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!