新手入门介绍线程锁<连载04>

/*
在生产者生产后,cpu重新分配

生产者可以重新获得cpu。

需求:
在生产者生产后,激活消费者cpu,让消费者去消费
而不是继续生产者获得cpu,以完成交替


上述问题小小的补充(升级线程数量)
建立两个消费者 两个生产者
*/


import java.lang.Thread.*;


class ThreadAdvanceLock4
{
	public static void main(String[]  args)
	{
		Resource resource = new Resource();
		
		Consumer consumer = new Consumer(resource);
		Consumer consumer2 = new Consumer(resource);
		
		Producer producer = new Producer(resource);
		Producer producer2 = new Producer(resource);
		
		Thread t1 = new Thread(consumer);
		Thread t2 = new Thread(consumer2);
		
		Thread t3 = new Thread(producer);
		Thread t4 = new Thread(producer2);
		
		t1.start();
		t2.start();
		
		t3.start();
		t4.start();
		
	}
}

class Resource
{
	private int  num;
	private String name;
	private boolean flagLock = false;
	
	//生产函数
	public synchronized void funPro(int num,String name)//加锁在执行期间,一直到执行完成后,才可以被夺得Cpu
	{
		if(flagLock)
			
		  try{this.wait();}
		  catch( InterruptedException interrupt)
		  {
			  System.out.println(interrupt.toString());
			  return;
		  }
		this.name = name;
		this.num = num;
		System.out.println("生产了商品..."+this.name+"..."+this.num);
		flagLock = true;
		this.notify();
	}
	//消费函数
	public synchronized void funCon()//同理
	{
		if(!flagLock)
		  try{this.wait();}
		  catch( InterruptedException interrupt)
		  {
			  System.out.println(interrupt.toString());
			  return;
		  }
		System.out.println("消费了商品..."+this.name+"..."+this.num);
		flagLock = false;
		this.notify();
	}
}

class Producer implements Runnable
{
	private Resource resource;
	private boolean flag = false;
	Producer(Resource resource)
	{
		this.resource = resource;
	}
	
	public void run()
	{
		while(true)
		{
			if(flag)
			{
				resource.funPro(1,"方便面");
				flag = false;
			}
			else
			{
				resource.funPro(2,"香肠");
			    flag = true;
			}
		}
	}
}

class Consumer implements Runnable
{
	private Resource resource;

	Consumer(Resource resource)
	{
		this.resource = resource;
	}
	
	public void run()
	{
		while(true)
	     resource.funCon();
	}
}

/**
问题分析:
生产了商品...香肠...2
消费了商品...香肠...2
消费了商品...香肠...2
生产了商品...方便面...1
消费了商品...方便面...1
消费了商品...方便面...1


参考图片:1-3


下一个实例解决此类问题



你可能感兴趣的:(java,线程)