モリス:
public class ObjectPropertiesVolatileTest {
static Cup cup = new Cup();
public static void changeColor() {
cup.setColor("black"); // change color of cup to black
}
public static void main(String[] args) {
cup.setColor("red"); // initialize color of cup as red
for(int i = 0; i < 3; i++) {
new Thread(){
public void run() {
for(int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName()
+ " " + i + " is " + cup.getColor());
if(Thread.currentThread().getName().equals("Thread-1"))
changeColor(); // Thread-1 changes the color of cup
for(int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName()
+ " " +i + " is " + cup.getColor());
}
}.start();
}
}
}
class Cup {
private volatile String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
私の質問は:どのようにフィールドを保証するためにcolor
のみ使用し、他のスレッドに表示されているオブジェクトカップのをvolatile
、キーワードの代わりに、同期やロックを使用していますか?
Kartik:
私はそれが正常に動作していると信じています。問題は、印刷は、内の文字列のマージ、声明を印刷するために呼び出すことでSystem.out.println(Thread.currentThread().getName() + " " +i + " is " + cup.getColor());
同期されていないなど、。
私は通話の時間を記録するためにあなたのゲッター/セッターにprint文を追加しました: -
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;
}
それが印刷された内容の抜粋: -
.
.
.
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
.
.
.
あなたが心配している問題は、この行です: - Thread-0 5 is red
それは印刷されているはずですblack
よね?
他のスレッドが値を変更する前に、まあ、このスレッドはゲッターに入りました。これは、これらの線から明らかです: -
-------------------------get Thread-0red 1356826035894581
-------------------------set Thread-1blackred 1356826036165653
正しく値を読み取るが、それは彼らが何をしていたことで、他のスレッドにかかる時間に比べて長い時間がかかった後に処理が行われ、それはそう。
私が間違っている場合、誰かが私を修正するためにハッピー。:)