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

链接上篇:

/*

在生产者生产后,cpu重新分配
生产者可以重新获得cpu。

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

*/

import java.lang.Thread.*;


class ThreadAdvanceLock3
{
	public static void main(String[]  args)
	{
		Resource resource = new Resource();
		
		Consumer consumer = new Consumer(resource);
		Producer producer = new Producer(resource);
		
		Thread t1 = new Thread(consumer);
		Thread t2 = new Thread(producer);
		
		t1.start();
		t2.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
生产了商品...方便面...1
消费了商品...方便面...1
生产了商品...香肠...2
消费了商品...香肠...2
生产了商品...方便面...1
消费了商品...方便面...1
生产了商品...香肠...2
消费了商品...香肠...2
生产了商品...方便面...1
消费了商品...方便面...1
生产了商品...香肠...2
消费了商品...香肠...2
生产了商品...方便面...1
消费了商品...方便面...1
生产了商品...香肠...2
消费了商品...香肠...2
生产了商品...方便面...1
消费了商品...方便面...1
*/

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