Java多线程的单生产单消费和多生产多消费问题的解决

单生产单消费:

/*
生产者和消费者:等待唤醒机制
*/
class Resource
{
	//定义一个商品的名字
	private String name;
	private int count=1;
	private boolean flag;
	public synchronized void set(String name)
	{
		if(flag)
			try{wait();}catch(Exception e){}
			this.name=name+"-----"+count;
			count++;
			System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);
			flag=true;
			notify();
	}
	public synchronized void get()
	{
		synchronized(this)
		{
		if(!flag)
			try{wait();}catch(Exception e){}
		System.out.println(Thread.currentThread().getName()+"消费了..."+this.name);
		flag=false;
		notify();
		}
	}
}

//定义生产者的任务
class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
			r.set("蛋糕");
		}
	}
}

class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
			r.get();
		}
	}
}
class  ThreadDemo_Producer_Consumer
{
	public static void main(String[] args) 
	{
		Resource r=new Resource();
		Producer p=new Producer(r);
		Consumer c=new Consumer(r);
		Thread t1=new Thread(p);
		Thread t2=new Thread(c);
		t1.start();
		t2.start();
	}
}
多生产多消费:

/*
多生产者和多消费者:等待唤醒机制
*/
class Resource
{
	//定义一个商品的名字
	private String name;
	private int count=1;
	private boolean flag;
	public synchronized void set(String name)
	{
		while(flag)
			try{wait();}catch(Exception e){}
		this.name=name+"-----"+count;
		count++;
		System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);
		flag=true;
		notifyAll();
	}
	public synchronized void get()
	{
		while(!flag)
			try{wait();}catch(Exception e){}
		System.out.println(Thread.currentThread().getName()+"消费了..."+this.name);
		flag=false;
		notifyAll();
	}
}

//定义生产者的任务
class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
			r.set("蛋糕");
		}
	}
}

class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
			r.get();
		}
	}
}
class  ThreadDemo_Producer_Consumer2
{
	public static void main(String[] args) 
	{
		Resource r=new Resource();
		Producer p=new Producer(r);
		Consumer c=new Consumer(r);
		Thread t1=new Thread(p);
		Thread t2=new Thread(c);
		Thread t3=new Thread(p);
		Thread t4=new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}


你可能感兴趣的:(多线程,线程安全,生产,消费)