4つのスレッド、2つは毎回1をプラスして、2つは毎回1を減らします

2463 ワード


package threadTest;

public class MultiThreadShareDemo {

	public static void main(String[] args) throws Exception {

		Data data = new Data();

		Plus p = new Plus(data);
		Cut c = new Cut(data);

		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);

		Thread t3 = new Thread(c);
		Thread t4 = new Thread(c);

		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}
}

/**
 *     
 * @author jingfn
 *
 */
 class Data{
	 private int data;
	 private boolean flag;
	 private int count = 2;

	public synchronized Data plus(Data dataIns){
		while(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		dataIns.data = dataIns.data - 1;
		dataIns.count = dataIns.count - 1;
		System.out.println(Thread.currentThread().getName()+"--plus--------"+dataIns.data+"---"+dataIns.count);
		if(dataIns.count <= 0){
			dataIns.flag = true;
			this.notifyAll();
		}
		return dataIns;
	}

	public synchronized Data cut(Data dataIns){
		while(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		dataIns.data = dataIns.data + 1;
		dataIns.count = dataIns.count + 1;
		System.out.println(Thread.currentThread().getName()+"--cut--"+dataIns.data+"---"+dataIns.count);
		if(dataIns.count >= 2){
			dataIns.flag = false;
			this.notifyAll();
		}
		return dataIns;
	}

 }

 /**
  *    
  * @author jingfn
  *
  */
 class Plus implements  Runnable {
	 private Data instance;
	 public Plus(Data instance){
		 this.instance = instance;
	 }
	 public void run(){
		 while(true){
			 instance.plus(instance);
		 }
	 }
 }

 /**
  *    
  * @author jingfn
  *
  */
 class Cut implements  Runnable {
	 private Data instance;
	 public Cut(Data instance){
		 this.instance = instance;
	 }
	 public void run(){
		 while(true){
			 instance.cut(instance);
		 }
	 }
 }