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

链接上篇

/*

探索升级版的锁的应用:
先采用Synchronized解决上述问题
采用同步函数解决此问题

*/


import java.lang.Thread.*;


class ThreadAdvanceLock2
{
	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;
	//生产函数
	public synchronized void funPro(int num,String name)//加锁在执行期间,一直到执行完成后,才可以被夺得Cpu
	{
		this.name = name;
		this.num = num;
		System.out.println("生产了商品..."+this.name+"..."+this.num);
	}
	//消费函数
	public synchronized void funCon()//同理
	{
		System.out.println("消费了商品..."+this.name+"..."+this.num);
	}
}

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();
	}
}

/**
现象分析:
解决了上述现象:
但是出现了新的问题:
在生产者生产后,cpu重新分配
生产者可以重新获得cpu,

这个问题下一次连载
参见1-2
*/

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