In fact, the communication between multiple threads is that multiple threads operate the same resource, but the operation actions are different.
The first thread writes the count, and the other thread takes the value of the read count. It reads and writes one operation.
class Res{ public String username; public String sex; } class Out extends Thread{ Res res; public Out(Res res){ this.res=res; } @Override public void run() { //Write operation int count=0; while (true){ // synchronized (res.getClass()){ if(count==0){//Even numbers res.username="Xiao Ming"; res.sex="male"; } else {//Odd number res.username="Xiaohong"; res.sex="female"; } count=(count+1)%2; // } } } } class Input extends Thread{ Res res; public Input(Res res){ this.res=res; } @Override public void run() { while (true){ // synchronized (res.getClass()){ System.out.println(res.username+","+res.sex); // } } } } public class OutInputThread { public static void main(String[] args) { Res res = new Res(); Out out = new Out(res); Input input = new Input(res); out.start(); input.start(); } }
The output is as follows:
Xiaoming, male
Xiaoming, female
Xiaohong, female
Xiaoming, male
Data format error????? System.out.println(res.username+","+res.sex);Input may change the value of Res object to small red / small Ming when outputting username, which leads to confusion of sex. In other words, in multi-threaded environment, thread safety may occur when reading and writing the same resource, and visibility does not have atomicity.
For specific reasons, please refer to Java Memory Model... https://blog.csdn.net/qq_37049496/article/details/81172330
How to solve it? Synchronization is also required for both threads. Uncomment can ensure that there is only one thread for the operation of shared resource res at the same time..