1. 程式人生 > >執行緒(四)

執行緒(四)

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生產者和消費者案例
 * @author fanfan
 *
 */
public class TestProductorAndConsumer3 {

	public static void main(String[] args) {
		Clerk2 cle = new Clerk2();
		Productor2 pr = new Productor2(cle); 
		
		Consumer2 cr = new Consumer2(cle);
		
		new Thread(pr,"生產者A").start();
		new Thread(cr,"消費者B").start();
		
		new Thread(pr,"生產者A1").start();
		new Thread(cr,"消費者B1").start();
		
		new Thread(pr,"生產者A3").start();
		new Thread(cr,"消費者B3").start();
		
		
		new Thread(pr,"生產者A4").start();
		new Thread(cr,"消費者B4").start();
		
		new Thread(pr,"生產者A5").start();
		new Thread(cr,"消費者B5").start();
		
		new Thread(pr,"生產者A7").start();
		new Thread(cr,"消費者B7").start();
		
	}
}

class Clerk2{
	private int product = 0;
	//採用同步鎖  就不使用synchronize
	private Lock lock = new ReentrantLock();
	//
	private Condition condition = lock.newCondition();
	//進貨
	public void get() throws InterruptedException{
		lock.lock();
		try {
			while(product>=1){ //為了避免虛假喚醒問題,應該總是使用在迴圈中
				System.out.println("產品已滿");
				try {
					condition.await();
				} catch (InterruptedException e) {
					// TODO: handle exception
				}
			}
			
			System.out.println(Thread.currentThread().getName()+":"+ ++product);
			condition.signalAll();
		} finally {
			// TODO: handle finally clause
			lock.unlock(); 
		}
		
	}
	//賣貨
	public void sale() throws InterruptedException{
		lock.lock();
		try {
		
			while(product <=0){
				System.out.println("缺貨");
				try {
					condition.await();
				} catch (InterruptedException e) {
					// TODO: handle exception
				}
			}
			System.out.println(Thread.currentThread().getName()+":"+ --product);
			condition.signalAll();
		} finally {
			// TODO: handle finally clause
			lock.unlock();
		}
		
		
		
	}
	
}

//生產者
class Productor2 implements Runnable{
	private Clerk2 clerk;
	
	public Productor2(Clerk2 clerk){
		this.clerk = clerk;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0;i<20;i++){
			try {
				Thread.sleep(200);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				clerk.sale();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

//消費者
class Consumer2 implements Runnable{

	private Clerk2 clerk;
	public Consumer2(Clerk2 clerk){
		this.clerk = clerk;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0;i<20;i++){
			try {
				clerk.get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}