public class Test {
public static void main (String[] args) throws java.lang.Exception
{
Resource resource=new Resource();
AddThread at=new AddThread(resource);
SubThread st=new SubThread(resource);
new Thread(at,"加法线程A").start();
new Thread(at,"加法线程B").start();
new Thread(st,"减法线程X").start();
new Thread(st,"减法线程Y").start();
// System.out.println("hi");
}
}
class Resource{
int num;
boolean flag=true;//true为标识可以进行加法操作无法进行减法操作,false为可以进行减法操作无法进行加法操作
public synchronized void add() throws Exception{
if (this.flag==false){
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println("加法操作,"+Thread.currentThread().getName()+",this.num="+this.num);
this.flag=false;
super.notifyAll();
}
public synchronized void sub() throws Exception{
if(this.flag==true){
super.wait();
}
Thread.sleep(200);
this.num--;//这个程序不加this结果就不对,不理解
System.out.println("减法操作,"+Thread.currentThread().getName()+",this.num="+this.num);
this.flag=true;
super.notifyAll();
}
}
class AddThread implements Runnable{
Resource resource;
public AddThread(Resource resource){
this.resource=resource;
}
@Override
public void run(){
for(int x=0;x<10;x++){
try{
this.resource.add();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable{
Resource resource;
public SubThread(Resource resource){
this.resource=resource;
}
@Override
public void run(){
for(int x=0;x<10;x++){
try{
this.resource.sub();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
要是哪个语言有这样的特性,那这语言早就死了;
简单一点的改法 把if 换成while
if(this.flag==true)
换成 while(this.flag==true)
if(this.flag==false)
换成 while(this.flag==false)