java多线程——多生产者消费者问题No1


需求:多生产者、多消费者问题
四个线程操作一个资源对象,两个线程操作生产,两个操作消费
在同步的部分使用的是synchronized,使用while, notifyAll解决多生产者、多消费者死锁问题



class Resource//资源
{
	private String name;
	private int count=1;
	private boolean flag=false;//标记
	public synchronized void set(String name)//同步函数
	{
		while(flag)//标记位
			try{this.wait();}catch(InterruptedException e){}
		this.name=name+count;//给名字加上编号
		count++;
		System.out.println(Thread.currentThread().getName()+"........生产者........."+this.name);
		flag=true;
		this.notifyAll();//唤醒
	}
	public synchronized void get()//同步函数
	{
		while(!flag)
			try{this.wait();}catch(InterruptedException e){}
		System.out.println(Thread.currentThread().getName()+"..消费者.."+name);
		flag=false;
		this.notifyAll();//唤醒
	}
}

class Input implements Runnable//生产
{
	Resource r;
	Input(Resource r)//构造函数
	{
		this.r=r;
	}
	public void run()//覆盖Runnable接口方法
		{
			while(true)
			{
				r.set("烤鸭");
			}	
		}
}

class Output implements Runnable//消费
{
	Resource r;
	Output(Resource r)//构造函数
	{
		this.r=r;
	}
	public void run()//覆盖Runnable接口方法
	{
		while(true)
		{
			r.get();
		}
	}
}

class ResourceDemo 
{
	public static void main(String[] args) 
	{
		Resource r=new Resource();//创建资源对象
		Input i=new Input(r);//创建线程任务对象
		Output o=new Output(r);//创建线程任务对象
		Thread t0=new Thread(i);//创建线程
		Thread t1=new Thread(i);
		Thread t2=new Thread(o);
		Thread t3=new Thread(o);
		t0.start();//开启线程
		t1.start();
		t2.start();
		t3.start();
	}
}

猜你喜欢

转载自blog.csdn.net/TDOA1024/article/details/81385392
今日推荐