以下程序执行基本的多线程任务。我在一个类中有两个线程。一个线程负责增加一个值变量,另一个线程负责检查该值并显示一条消息。
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 线程永远不会告诉该值已达到。我不懂为什么。