多线程实现一边加一遍减 1package cn.cccc.demo;2class AddThread implements Runnable{3 private Resource res;4 public AddThread(Resource res) {5 this.res = res;6 // TODO Auto-generated constructor stub7 }8 @Override9 public void run() {10 // TODO Auto-generated method stub11 for(int x= 0; x < 50 ; x++){12 try {13 this.res.add();14 } catch (Exception e) {15 // TODO Auto-generated catch block61 collapsed lines16 e.printStackTrace();17 }18 }19 20 }21}22class SubThread implements Runnable{23 private Resource res;24 public SubThread(Resource res) {25 this.res = res;26 // TODO Auto-generated constructor stub27 }28 @Override29 public void run() {30 // TODO Auto-generated method stub31 for(int x= 0; x < 50 ; x++){32 try {33 this.res.sub();34 } catch (Exception e) {35 // TODO Auto-generated catch block36 e.printStackTrace();37 }38 }39 40 }41}42class Resource { // 定义一个操作的资源43 private int num ; // 这个是要进行加减的元数据44 private boolean flag = false; // 加减的切换45 46 public synchronized void add() throws Exception{ // 加法47 if(this.flag == false){ //现在需要执行的减法操作,加法操作等待48 super.wait();49 }50 51 Thread.sleep(100);52 this.num++;53 System.out.println("[加法操作 - ]" + Thread.currentThread().getName() + "] num = " + this.num);54 this.flag = false;55 super.notifyAll();56 }57 public synchronized void sub() throws Exception{58 if(this.flag == true){59 super.wait();60 }61 Thread.sleep(200);62 this.num --;63 System.out.println("[减法操作 - ]" + Thread.currentThread().getName() + "] num = " + this.num);64 this.flag = true;65 super.notifyAll();66 }67}68public class ThreadDemo {69 public static void main(String[] args) throws Exception{70 Resource res =new Resource();71 AddThread at = new AddThread(res);72 SubThread st = new SubThread(res);73 new Thread(at, "加法线程").start();74 new Thread(st, "减法线程").start();75 }76} 设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台,如果没有新电脑生产则不搬,如果电脑没被搬走则不生产,并统计出生产的电脑数量。