在jdk1.8下运行多线程的数字加减案例,为什么执行结果不是想要的,正常应该只能输出0,-1,1
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();
}
}
}
}
运行结果及报错内容
求帮忙解答一下,是jdk1.8新机制导致的吗