[java多线程]数字加减 代码

问题概述:设计四个线程对象,两个线程实现加操作,两个线程实现减操作

注意一个问题:经常会用if(this.flag==false)来判断,用if并不能实现进程同步,会出现负数。

 class Resource{
	private int num=0;//
	private boolean flag=true;//加减操作
	public synchronized void add() throws InterruptedException {
		while(this.flag==false) {
			super.wait();
		}
		Thread.sleep(400);
		this.num++;
		System.out.println("【加法操作】"+
		Thread.currentThread().getName()
				+"num="+this.num);
		this.flag=false;
		super.notifyAll();
	}
	public synchronized void sub() throws InterruptedException {
		while(this.flag==true) {
			super.wait();
		}
		Thread.sleep(600);
		this.num--;
		System.out.println("【减法操作】"+
		Thread.currentThread().getName()
		+"num="+this.num);
		this.flag=true;
		super.notifyAll();
	}
} 
 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 (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
	}
	
} 
 

class SubThread  implements Runnable{
	private Resource resource;
	public SubThread(Resource resource) {
		this.resource=resource;
	}
	@Override
	public void run() {
		for(int x=0;x<50;x++) {
			try {
				this.resource.sub();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
 
public class Test1 {
 public static void main(String[] args) throws Exception {
		Resource resource = new Resource();
		SubThread st = new SubThread(resource);
		AddThread at = new AddThread(resource);
		new Thread(at, "减法线程-A").start();
		new Thread(at, "减法线程-B").start();
	    
		new Thread(st, "加法线程-a").start();
		new Thread(st, "加法线程-b").start();
		 
}
}
posted @ 2020-04-11 00:04  下饭  阅读(734)  评论(0编辑  收藏  举报