자바 생산 소비자 인 스 턴 스 -- > 업그레이드 버 전

import java.util.concurrent.locks.*;

/*
	Java     :      (          )

	    jdk1.5        :

	 Lock   sychronized
	 Condition         Object        (wait,notify,notifyAll)
	
	Author:renpingqing

	Date:2013 7 7  12:22:42
	
	  :
		1、       ,   ,      ,      
		2、        Runnable            
		3、        Runnable            
			(1)            ,             ,    
		4、           ,     ,     ,     
*/

class Resource {
	private String name; //    
//	private int num = 1; //    

	private int num = 1; //    
	private boolean flag = false; //    ,false       

	private Lock lock = new ReentrantLock(); //     

	private Condition condition_pro = lock.newCondition();
	private Condition condition_con = lock.newCondition();
	
	//    

	public void producer(String name) throws InterruptedException {
		lock.lock(); //  
		try {
			while(flag) {
				condition_pro.await(); //     
			}
			this.name = name + "    :" + num++; 
			System.out.println(Thread.currentThread().getName() + "--  --" + "    :" + this.name);
	
			flag = true;
			condition_con.signal(); //     
		} finally {
			lock.unlock(); //  
		}
	}

	//    

	public synchronized void consumer() throws InterruptedException {
		lock.lock();
		try {
			while(!flag) {
				condition_con.await();
			}
			System.out.println(Thread.currentThread().getName() + "+++++  +++++" + name);
			flag = false;
			condition_pro.signal();
		} finally {
			lock.unlock();
		}
	}
}

//   

class Producer implements Runnable {
	private Resource res;
	
	//    

	public Producer(Resource res) {
		this.res = res;
	}
	
	//  run  

	public void run() {
		while(true) {
			try {
				res.producer("     ");
			} catch(InterruptedException e) {
			
			}
		}
	}
}

//   

class Consumer implements Runnable {
	private Resource res;
	
	public Consumer(Resource res) {
		this.res = res;
	}

	public void run() {
		while(true) {
			try {
				res.consumer();
			} catch(InterruptedException e) {
			
			}
		}
	}
}

//   

class ProducerConsumer2 {
	public static void main(String[] args) {

		//    

		Resource r = new Resource();
		
		//     

		Producer p1 = new Producer(r);
		Producer p2 = new Producer(r);
		Producer p3 = new Producer(r);
		Producer p4 = new Producer(r);

		//     

		Consumer c1 = new Consumer(r);
		Consumer c2 = new Consumer(r);
		Consumer c3 = new Consumer(r);
	
		//       

		Thread t1 = new Thread(p1);
		Thread t2 = new Thread(p2);
		Thread t3 = new Thread(p3);
		Thread t4 = new Thread(p4);
		
		//       

		Thread t10 = new Thread(c1);
		Thread t11 = new Thread(c2);
		Thread t12 = new Thread(c3);
		
		//    

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

		t10.start();
		t11.start();
		t12.start();
	}
}

좋은 웹페이지 즐겨찾기