[java多线程]数字加减 代码
问题概述:设计四个线程对象,两个线程实现加操作,两个线程实现减操作
注意一个问题:经常会用if(this.flag==false)来判断,用if并不能实现进程同步,会出现负数。
class Resource{
private int num=0;//
private boolean flag=true;//加减操作
public synchronized void add() throws InterruptedException {
while(this.flag==false) {
super.wait();
}
Thread.sleep(400);
this.num++;
System.out.println("【加法操作】"+
Thread.currentThread().getName()
+"num="+this.num);
this.flag=false;
super.notifyAll();
}
public synchronized void sub() throws InterruptedException {
while(this.flag==true) {
super.wait();
}
Thread.sleep(600);
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 x=0;x<50;x++) {
try {
this.resource.add();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable{
private Resource resource;
public SubThread(Resource resource) {
this.resource=resource;
}
@Override
public void run() {
for(int x=0;x<50;x++