public class ProjectDemo {
public static void main(String[] args) {
Resource res = new Resource();
AddThread at = new AddThread(res);
SubThread st = new SubThread(res);
new Thread(at, "加法线程-A")。start();
new Thread(st, "减法线程-B")。start();
new Thread(at, "加法线程-X")。start();
new Thread(st, "减法线程-Y")。start();
}
}
class Resource{ //定义一个操作的资源
private int num; //要进行加减操作的数据
private boolean flag = true; //加减的切换
//flag:true 可以进行加操作,不能进行减操作
//flag:false 可以进行减操作,不能进行加操作
public synchronized void add() throws Exception{ //执行加法操作
Thread.sleep(100); //加入延迟便于观察问题
this.num++;
System.out.println("【加法操作" + Thread.currentThread().getName() + "】num = " + this.num);
}
public synchronized void sub() throws Exception{ //执行减法操作
Thread.sleep(200);
this.num--;
System.out.println("【减法操作" + Thread.currentThread().getName() + "】num = " + this.num);
}
}
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 (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SubThread 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.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
用的是eclipse,提示说the type Runnable cannot be the superinterface of AddThread, a superinterface must be a interface.
求大家指教 ,谢谢