多线程实现一边加一遍减
package cn.cccc.demo;class AddThread implements Runnable{ private Resource res; public AddThread(Resource res) { this.res = res; // TODO Auto-generated constructor stub } @Override public void run() { // TODO Auto-generated method stub for(int x= 0; x < 50 ; x++){ try { this.res.add(); } catch (Exception e) { // TODO Auto-generated catch block61 collapsed lines
e.printStackTrace(); } }
}}class SubThread implements Runnable{ private Resource res; public SubThread(Resource res) { this.res = res; // TODO Auto-generated constructor stub } @Override public void run() { // TODO Auto-generated method stub for(int x= 0; x < 50 ; x++){ try { this.res.sub(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}}class Resource { // 定义一个操作的资源 private int num ; // 这个是要进行加减的元数据 private boolean flag = false; // 加减的切换
public synchronized void add() throws Exception{ // 加法 if(this.flag == false){ //现在需要执行的减法操作,加法操作等待 super.wait(); }
Thread.sleep(100); this.num++; System.out.println("[加法操作 - ]" + Thread.currentThread().getName() + "] 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 --; System.out.println("[减法操作 - ]" + Thread.currentThread().getName() + "] num = " + this.num); this.flag = true; super.notifyAll(); }}public class ThreadDemo { public static void main(String[] args) throws Exception{ Resource res =new Resource(); AddThread at = new AddThread(res); SubThread st = new SubThread(res); new Thread(at, "加法线程").start(); new Thread(st, "减法线程").start(); }}设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台,如果没有新电脑生产则不搬,如果电脑没被搬走则不生产,并统计出生产的电脑数量。