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

新手入门介绍线程锁:

探索升级版的锁的应用:

1.lock覆盖了Synchronized方法,可以支持多个Condition对象 
2.锁是控制多个线程对共享资源进行访问的工具。
3.Condition覆盖了对象的wait(),notify(),notifyAll()方法

4.可以唤醒对方线程

import java.lang.Thread.*;

/*
实例:
两个线程:生产者(Producer)和消费者(Consumer)
资源(Resource)

*/
class ThreadAdvanceLock
{
	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 void funPro(int num,String name)
	{
		this.name = name;
		this.num = num;
		System.out.println("生产了商品..."+this.name+"..."+this.num);
	}
	//消费函数
	public 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();
	}
}
/**
现象分析:
生产了商品...方便面...1
生产了商品...香肠...2
消费了商品...方便面...1
具体分析:参见1-1



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