Synchronized和ReentrantLock

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


public class StudyJava {
	Buffer mBuffer = new Buffer(5);;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		StudyJava s = new StudyJava();
		Productor p = s.new Productor();
		Consumer c = s.new Consumer();
		Thread tp = new Thread(p);
		Thread tc = new Thread(c);
		tc.start();
		tp.start();
	}
	
	class Productor implements Runnable{
		public void run() {
			while(true){
			    int i = (int)(Math.random()*1000);
			    mBuffer.add(i);
			    System.out.println("add " + i);
			}
		}		
	}
	class Consumer implements Runnable{
		public void run() {
			while(true){
			    int i = mBuffer.get();
			    System.out.println("del " + i);
			}
		}
		
	}	
}






class Buffer {
	LinkedList<Integer> buffer;
	int mSize;
	int currentSize = 0;
	ReentrantLock lock = new ReentrantLock();
	Condition c = lock.newCondition();//这儿只new了一个condition,因为add/get要在同一个condition上await/signal
	
	public Buffer(int size) {
		buffer = new LinkedList<Integer>();
		mSize = size;
	}
	
	synchronized void addElement(int i) {
		if (currentSize >= mSize) {
		    try {
		        System.out.println("full");	
		        wait();	
		    } catch(Exception e) {
		    	
		    }
		}
		currentSize++;
		buffer.add(i);
		notifyAll();
	}
	synchronized int getElement() {
		if (currentSize <= 0) {
		    try {
		    	System.out.println("empty");		
		        wait();	
		    } catch(Exception e) {
		    	
		    }
		}
		currentSize--;
		int i = buffer.remove();
		notifyAll();
		return i;
	}
	
	void add(int i) {
		lock.lock();
		if (currentSize >= mSize) {
		    try {
		        System.out.println("full");	
		        c.await();//和condition,lock对应的不能使用wait方法,只能使用await/signal,wait/notify只能用于同步方法	
		    } catch(Exception e) {
		    	
		    }
		}
		currentSize++;
		buffer.add(i);
		c.signalAll();
		lock.unlock();
		
	}
	int get() {
		lock.lock();
		if (currentSize <= 0) {
		    try {
		    	System.out.println("empty");		
		        c.await();	
		    } catch(Exception e) {
		    	
		    }
		}
		currentSize--;
		int i = buffer.remove();
		c.signalAll();
		lock.unlock();
		return i;
	}	
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值