简单的生产者与消费者实现

同步堆栈,用于存储。

public class SyncStack {
	private int index = 0;
	private char[] data = new char[6];
	
	public synchronized void push(char c){
		while(index == data.length){
			try{
				this.wait();
			}catch(InterruptedException e){
			}
		}
		this.notify();
		data[index] = c;
		index ++;
		System.out.println("Produced:" + c);
	}
	
	public synchronized char pop(){
		while(index == 0){
			try{
				this.wait();
			}catch(InterruptedException e){
			}
		}
		this.notify();
		index--;
		System.out.println("Consume:" + data[index]);
		return data[index];
	}
}

生产者线程:

public class Producer implements Runnable{
	SyncStack stack;
	public Producer(SyncStack stack){
		this.stack = stack;
	}
	public void run(){
		for(int i=0; i<20; i++){
			char c = (char)(Math.random()*26 + 'A');
			stack.push(c);
			try{
				Thread.sleep((int)Math.random()*300);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
}

  消费者线程:

public class Consumer implements Runnable{
	private SyncStack stack;

	public Consumer(SyncStack stack){
		this.stack = stack;
	}
	public void run(){
		for(int i=0; i<20; i++){
			char c = stack.pop();
			try{
				Thread.sleep((int)Math.random()*300);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
}

    测试:

public class SyncTest {
	public static void main(String args[]){
		SyncStack stack = new SyncStack();
		Runnable p = new Producer(stack);
		Runnable c = new Consumer(stack);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
	}
}
 

wait() 和 notify() 方法的特性决定了它们经常和synchronized 方法或块一起使用,将它们和操作系统的进程间通信机制作 一个比较就会发现它们的相似性:synchronized方法或块提供了类似于操作系统原语的功能,它们的执行不会受到多线程机制的干扰,而这一对方法则 相当于 block 和wakeup 原语(这一对方法均声明为 synchronized)。它们的结合使得我们可以实现操作系统上一系列精妙的进程间 通信的算法(如信号量算法),并用于解决各种复杂的线程间通信问题。

关于 wait() 和 notify() 方法最后再说明两点:

    第一:调用 notify() 方法导致解除阻塞的线程是从因调用该对象的 wait() 方法而阻塞的线程中随机选取的,我们无法预料哪一个线程将会被选择,所以编程时要特别小心,避免因这种不确定性而产生问题。

    第二:除了 notify(),还有一个方法 notifyAll() 也可起到类似作用,唯一的区别在于,调用 notifyAll() 方法将把因调 用该对象的 wait() 方法而阻塞的所有线程一次性全部解除阻塞。当然,只有获得锁的那一个线程才能进入可执行状态。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值