码迷,mamicode.com
首页 > 编程语言 > 详细

java 线程七-Lock锁

时间:2016-05-12 20:54:11      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

JDK1.5中提供了多线程升级解决方案。
将同步synchronized替换成显式Lock操作。
将Object中的wait,notify,notifyAll,替换成了condition对象。该对象可以通过Lock锁进行获取。
一个Lock锁可以生成多个condition对象。

该示例中实现了本方只唤醒对方的操作。


import java.util.concurrent.locks.*;
class Resource
{
	private String name;
	private int num=0;
	boolean flag;

	private Lock lock=new ReentrantLock();
	private Condition condition_set=lock.newCondition();
	private Condition condition_get=lock.newCondition();
	
	public void set(String name) throws InterruptedException
	{
		lock.lock();
		try
		{
			while(flag)
				condition_set.await();
			this.name=name+"_"+num++;
			System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
			flag=true;
			condition_get.signal();
		}
		finally
		{
			lock.unlock();
		}
	}
	public void get() throws InterruptedException
	{
		lock.lock();
			try
			{
				while(!flag)
					condition_get.await();
				System.out.println(Thread.currentThread().getName()+"消费者.............."+this.name);
				flag=false;
				condition_set.signal();
			}
			finally
			{
				lock.unlock();
			}
	}
}

class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while (true)
		{
			try
			{
				r.set("商品");
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}

class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while (true)
		{
			try
			{
				r.get();
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}

class ProducerConsumerDemo1 
{
	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(p);
		Thread t3=new Thread(c);
		Thread t4=new Thread(c);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		System.out.println("Hello World!");
	}
}


java 线程七-Lock锁

标签:

原文地址:http://blog.csdn.net/iemdm1110/article/details/51357107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!