I have a simple program to test for multi-thread in java
public class Test {
public static void main(String[] args) {
final Data data = new Data();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
for (int j = 0; j < 5; j++) {
data.set(new Random().nextInt(30));
}
}
}).start();
}
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
for (int j = 0; j < 5; j++) {
data.get();
}
}
}).start();
}
}
}
class Data {
private int data;
public void set(int data) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ready to write data");
this.data = data;
System.out.println(Thread.currentThread().getName() + " write " + this.data);
}
public void get() {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ready to read data");
System.out.println(Thread.currentThread().getName() + " read " + this.data);
}
}
The result is random, while in one time, I got the result like that:
Thread-3 ready to read data
Thread-2 ready to write data
Thread-1 ready to write data
Thread-0 ready to write data
Thread-0 write 20
Thread-4 ready to read data
Thread-1 write 10
Thread-5 ready to read data
Thread-2 write 10
Thread-3 read 0
Thread-5 read 20
Thread-4 read 20
etc
I'm puzzled about that, the data variable in Data class is shared by all threads, while the last write operation is Thread-2 write 10, I think the data value should be 10 now, why Thread-3 read 0, Thread-5 and Thread-4 read 20? I think they should read 10
while, you're right, I should add volatile for data variable, but after that, the result becomes:
Thread-0 ready to write data
Thread-2 ready to write data
Thread-3 ready to read data
Thread-1 ready to write data
Thread-5 ready to read data
Thread-5 read 22
Thread-3 read 16
Thread-4 ready to read data
Thread-2 write 16
Thread-0 write 22
etc
why the read operation can be ahead of write operation, 22 and 16 is read before they are write, at least the print value shows that