+ 1
Why output for every thread is 0?
MultipleThread on volatile https://code.sololearn.com/cQXwdYBMFzyz/?ref=app
12 ответов
+ 2
Yes!! you are right!! The value i is already inside the loop ie.
for(int i=1; i<=5; i++) {
vt = new VolatileThread(vd, i);
}
See variable i is already there, I want this value of i to be printed in write() & read() method. Can you help it out??
+ 1
Hello Donna! Thanks for your response! Not only have I passed an object of class VolatileDemo as a parameter to the class VolatileThread but also the parameter 'int i' and with every pass of loop, a new value of parameter is also passed which in turn updates the variable i of class VolatileThread & that updated value of variable i of VolatileThread is passed as a parameter to the function call in class VolatileThread. But I don't get the desired output.
Obviously there may be some fault. Can you please pin point my mistake?
+ 1
Hello!! Donna. Have you find any way yet to solve that??
+ 1
Hello Donna!! Finally I have come with a solution. Instead of using == in (t.getName()=="Write"+i), if we use equal() operator in (t.getName().equals("Write"+i)), I am getting the desired ouput.
Strings can't be compared using any relational operator like ==, <, >, <=, >=.
Anyway, thanks a lot for your cooperation.
0
Write1 1
Read1 1
Write2 2
Read2 2
Write3 3
Read3 3
Write4 4
Read4 4
Write5 5
Read5 5
The sequence of this output may differ because you don't know which thread will execute first. But the content of output must be this.
0
For eg. You may also get
Write1 1
Write2 2,
Write3 3
Read1 3
Read2 3
Write4 4
Read3 4
Read4 4
Write5 5
Read5 5
It depends on the execution of thread-which thread will execute when....But there must be some numeric value for each thread instead of only 0.
0
No no dear....you are mistaken!!
What you have done is:
String str = "Write"+i+" "+i;
and you pass this as parameter.
Which means what you get as output, you have simply passed the output as input.
Moreover, What about the value 'i' ?
ie. vt = new VolatileThread (vd, i);
In the class VolatileThread, again this 'i' is passed as parameter in method call write(i) which then output the value of 'i' in System.out.println(t.getName + " " + i);
And this 'i' is missing in your System.out.println() statement in both write() & read() function. Please notice it.
As I have mentioned earlier in my comment, the sequence of output may change. But there must be some numeric value within the range of 1 to 5 for each thread, not only 0.
Write1, Write2.....Read1, Read2.... are only threads, not the value of 'i'. Read1 1 the latter 1 is the value of 'i'.