不经意间就写了个问题代码,多线程还是很有意思的哈
class Foo{
private int number=0;
void add(){
synchronized (this){
if(number==0){
System.out.println("add 1 "+(++number));
notify();
}else{
try {
System.out.println("add 1 wait");
wait();
System.out.println("add end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
void decrease(){
synchronized (this){
if(number==1){
System.out.println("dec 1 "+(--number));
notifyAll();
}else {
try {
System.out.println("dec 1 wait");
wait();
System.out.println("dec end");
//自己阻塞后,无人唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Foo foo = new Foo();
new Thread(()->{for (int i = 0; i < 2; i++) {foo.add();}},"A").start();
new Thread(()->{for (int i = 0; i < 2; i++) {foo.decrease();}},"B").start();
}
}