生产者和消费者线程实现

一生产与一消费:操作栈实现
package com.cn.ee;

import java.util.ArrayList;
import java.util.List;

class W{
	static List<String> list=new ArrayList<String>();
}

class PP{
	synchronized public void shengchan(){
		if(W.list.size()!=0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		W.list.add("aaaaa");
		System.out.println("set  list.size---->"+W.list.size());
		this.notify();
	}

	synchronized public void xiaofei(){
		if(W.list.size()==0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String s=W.list.get(0);
		W.list.remove(0);
		System.out.println("get  size()---->"+W.list.size());
		this.notify();
	}
}

class ThreadA extends Thread{
	PP p;
	public ThreadA(PP p) {
		// TODO Auto-generated constructor stub
		this.p=p;
	}
	public void run(){
		while(true){
			p.shengchan();
		}
	}
}
class ThreadB extends Thread{
	PP p;
	public ThreadB(PP p) 
	{
		this.p=p;
	}
	public void run(){
		while(true){
			p.xiaofei();
		}
	}
}

public class aaa {
		public static void main(String[] args) throws InterruptedException {
			PP p=new PP();
			ThreadA a=new ThreadA(p);
			a.start();
			ThreadB b1=new ThreadB(p);
			b1.start();
		}


} 

一生产多消费:操作站

将最后面那个aaa函数改为如下:

public class aaa {
		public static void main(String[] args) throws InterruptedException {
			PP p=new PP();
			ThreadA a=new ThreadA(p);
			a.start();
			ThreadB b1=new ThreadB(p);
			ThreadB b2=new ThreadB(p);
			ThreadB b3=new ThreadB(p);
			ThreadB b4=new ThreadB(p);
			ThreadB b5=new ThreadB(p);
			b1.start();
			b2.start();
			b3.start();
			b4.start();
			b5.start();
		}


}
会发生IndexOutOfBoundsExcepion异常,原因是,生产者进行生产之后,消费者进行消费,然后另外一个或多个消费者线程获得虚拟机,执行到wait方法,生产者进行生产,消费者进行消费,唤醒另外一个消费者线程,从一个空的list取出元素时发生异常。为了避免这种情况可以将PP类中的生产和消费方法中的if改成while就可以避免这种事情的发生。多生产一消费和多生产多消费同理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值