Resource类中的add()方法和sub()方法首先if判断flag状态,如果为true应该执行 this.wait()线程进入等待状态。如果为false执行else{}中的语句。按理说if(){}后的语句不用else{}扩起来应该不影响功能的实现,看视频老师就没用else{}括起来if后的语句,可是我的代码如果不用else{}把if后的语句扩起来就达不到效果。求解答是为什么!!琢磨了好久,能力有限没想明白。
public class AddSubThreadDemo {
public static void main(String[] args) {
Resource rsc = new Resource();
AddThread at = new AddThread(rsc);
SubThread st = new SubThread(rsc);
new Thread(at, "加法线程 - A").start();
new Thread(at, "加法线程 - B").start();
new Thread(st, "减法线程 - X").start();
new Thread(st, "减法线程 - Y").start();
}
}
class Resource {
private int num = 0;
private boolean flag = true; // 如果flag为true,执行加法操作;如果flag为false,执行减法操作。
//加法方法
public synchronized void add() throws Exception {
if (this.flag == false) {
super.wait();
}else { //这里的else{}去掉就会出现错误结果
Thread.sleep(100);
this.num++;
System.out.println("【加法操作 - " + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = false;
super.notifyAll();}
}
//减法方法
public synchronized void sub() throws Exception {
if (this.flag == true) {
super.wait();
}else { //这里的else{}去掉就会出现错误结果
Thread.sleep(200);
this.num--;
System.out.println("【减法操作 - " + Thread.currentThread().getName() + "】num = " + this.num);
this.flag = true;
super.notifyAll();}
}
}
//加法线程
class AddThread implements Runnable {
private Resource resource;
public AddThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.resource.add();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//减法线程
class SubThread implements Runnable {
private Resource resource;
public SubThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int j = 0; j < 100; j++) {
try {
this.resource.sub();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}