How does volatile keyword ensure an object`s fields are visible to other threads?

不想你离开。 提交于 2019-12-04 12:18:19

I believe it is working fine. The problem is that the printing, call to print statement, merging of strings in System.out.println(Thread.currentThread().getName() + " " +i + " is " + cup.getColor());, etc. are not synchronised.

I added print statements to your getters/setters to log the time of calls:-

public String getColor() {
    System.out.println("-------------------------get " + Thread.currentThread().getName() + this.color + " " + System.nanoTime());
    return color;
}

public void setColor(String color) {
    System.out.println("-------------------------set " + Thread.currentThread().getName() + color + this.color + " " + System.nanoTime());
    this.color = color;
}

A snippet of what it printed:-

.
.
.
Thread-0 4 is red
-------------------------get Thread-1red 1356826035808750
Thread-1 8 is red
-------------------------get Thread-2red 1356826035425706
Thread-2 2 is red
-------------------------get Thread-1red 1356826035963697
Thread-1 9 is red
-------------------------get Thread-0red 1356826035894581
-------------------------set Thread-1blackred 1356826036165653
-------------------------get Thread-2red 1356826036036858
Thread-2 3 is black
-------------------------get Thread-1black 1356826036219728
Thread-1 0 is black
Thread-0 5 is red
-------------------------get Thread-1black 1356826036402925
Thread-1 1 is black
-------------------------get Thread-2black 1356826036305139
Thread-2 4 is black
-------------------------get Thread-1black 1356826036535236
Thread-1 2 is black
.
.
.

The problem you are concerned about is this line:- Thread-0 5 is red It should have printed black, right?

Well, this thread entered the getter before the other thread changed the value. This is evident from these lines:-

-------------------------get Thread-0red 1356826035894581
-------------------------set Thread-1blackred 1356826036165653

So it read the value correctly but the processing done after that took a long time as compared to the time taken by other threads in doing what they were doing.

Happy for someone to correct me if I am wrong. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!