【发布时间】:2009-07-16 05:15:40
【问题描述】:
我遇到了 Synchronized 不符合我预期的问题,我也尝试使用 volatile 关键字:
共享对象:
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"
我不希望它们混在一起。
【问题讨论】:
-
你怎么能期待“在利比亚线程利比亚真棒”?您的程序不包含“真棒”一词
标签: java multithreading synchronized