以下程序執行基本的多線程任務。我在一個類中有兩個線程。一個線程負責增加一個值變量,另一個線程檢查值並顯示一條消息。爲什麼在多個線程之間不更新值?
Class Was{
private int ctime;
private int value;
public Thread w,c;
public was(int a) {
ctime=a;
w = new Thread(new Runnable() {
public void run() {
try {
for(int i=0;i<5;i++) {
Thread.sleep(ctime*1000);
value++;
}
System.out.printf("\nIncreasing done");
} catch(InterruptedException e) {
System.out.println(e);
}
}
});
c = new Thread(new Runnable() {
public void run() {
try {
for(;;) {
if(value==3) {
w.wait();
System.out.printf("\nValue reached");
w.notify();
break;
}
}
} catch(InterruptedException e) {
System.out.println(e);
}
}
});
}
main class
class Main{
public static void main(String z[]) {
Scanner s = new Scanner(System.in);
int temp;
System.out.printf("\nEnter the sleeping time in seconds: ");
temp=s.nextInt();
was m = new was(temp);
m.w.start();
m.c.start();
}
}
的C線程永遠不會告訴的價值已經達到了。我不懂爲什麼。
請遵循Java命名約定,類以大寫字母開頭。請格式化您的代碼。 –
這個[示例](http://arashmd.blogspot.com/2013/06/java-threading.html#synctr1)可能會有所幫助。 – 2013-10-18 12:44:09