I have an int x field, which is supposed to be accessed by many threads at the same time. I want x have a separate copy for each thread, each of which starts with the original value. I tried to do this using the volatile keyword, but each new thread still changes x for the other threads.
Here is a sample code:
public class StackOverflowThread0 { public StackOverflowThread0() { new A().start(); } public static void main(String[] args) { new StackOverflowThread0(); } volatile int x = 0;
output:
x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 x=1 | thread id=10| 100*x+x=101 //thread 10 has x field value as 1 x=2 | thread id=11| 100*x+x=202 //thread 11 modifies x field to 2 x=2 | thread id=10| 100*x+x=202 //thread 10 lost x value as 1 :( etc...
How to save a separate x value for each thread, or is there a better way to solve the problem?
java multithreading
user390525
source share