, 나 또한 휘발성 키워드를 사용하여 시도 :자바 동기화 및 스레드
공유 대상 :
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"
내가 그들을 혼합을 기대 해달라고.
어떻게 "리비아 스레드 리비아 굉장한"을 기대할 수 있습니까? 귀하의 프로그램에는 "awesome"이라는 단어가 없습니다. –