我已经设置了标志的值,但是结果不是'add'和'sub'交替出现。为什么?当我查看结果时,它执行了两次“ sub”方法。但是,当“ sub”方法结束时,标志的值将设置为“ false”。但是结果,它连续两次打印了“ subxxxxx”。
class Resource {
private boolean flag = true;
private int num = 0;
// At here I have declared an add()
public synchronized void add() throws InterruptedException {
if (this.flag == false) {
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println("addition:"+Thread.currentThread().getName() + this.num);
this.flag = false;
super.notifyAll();
}
// At here I have declared an sub()
public synchronized void sub() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
this.flag = true;
super.notifyAll();
}
}
/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
new Thread(ad, "add").start();
new Thread(ad, "add").start();
new Thread(sub, "sub").start();
new Thread(sub, "sub").start();
}
}
您似乎以为,当您的wait()
通话结束时,该电话flag
已更改为您要在致电之前拥有的电话wait()
。没有这样的保证,尤其是因为您涉及两个以上的线程。您应该检查是否需要继续等待。另请参见等待boolean值更改其状态
但是总的来说,这些结构太低了,无法使用(除非您想学习基本知识),并且您应该查看并发utils包,以获取更简单的高层结构(例如Queues,Latches,Conditions)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句