我在與同步行爲不我所期望的方式問題,我嘗試使用volatile關鍵字也:的Java同步和線程
共享對象
public class ThreadValue {
private String caller;
private String value;
public ThreadValue(String caller, String value) {
this.value = value;
this.caller = caller;
}
public synchronized String getValue() {
return this.caller + " " + this.value;
}
public synchronized void setValue(String caller, String value) {
this.caller = caller;
this.value = value;
}
}
主題1:
class CongoThread implements Runnable {
private ThreadValue v;
public CongoThread(ThreadValue v) {
this.v = v;
}
public void run() {
for (int i = 0; i < 10; i++) {
v.setValue("congo", "cool");
v.getValue();
}
}
}
螺紋2:
class CongoThread implements Runnable {
private ThreadValue v;
public CongoThread(ThreadValue v) {
this.v = v;
}
public void run() {
for (int i = 0; i < 10; i++) {
v.setValue("congo", "lame");
v.getValue();
}
}
}
調用類:
class TwoThreadsTest {
public static void main (String args[]) {
ThreadValue v = new ThreadValue("", "");
Thread congo = new Thread(new CongoThread(v));
Thread libya = new Thread(new LibyaThread(v));
libya.start();
congo.start();
}
}
偶爾我得到"In Libya Thread congo cool"
這絕不應該發生。我只希望:
"In Libya Thread libya awesome"
"In Congo Thread congo cool"
我不希望他們進行混合。
你怎麼能期待「在利比亞螺紋利比亞真棒」?你的程序不包含「真棒」 – 2009-07-16 05:30:25