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

/*
需求:
使用新功能 锁

代替上述程序

*/

import java.lang.Thread.*;
import java.util.concurrent.locks.*;

class ThreadAdvanceLock6
{
	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;
	
	Lock lock = new ReentrantLock();
	Condition condition_producer = lock.newCondition();
	Condition condition_consumer = lock.newCondition();
	
	//生产函数
	public void funPro(int num,String name)//加锁在执行期间,一直到执行完成后,才可以被夺得Cpu
	{
		    lock.lock();
			try
			{
			while(flagLock)
			     condition_producer.await();
			this.name = name;
			this.num = num;
			System.out.println("生产了商品..."+this.name+"..."+this.num);
			flagLock = true;
			condition_consumer.signal();
		    }
			catch(InterruptedException interrupted)
			{
				System.out.println(interrupted.toString());
			}finally
			{
				lock.unlock();
			}
	}	
	//消费函数
	public void funCon()//同理
	{
		lock.lock();
		try{
		        while(!flagLock)
				condition_consumer.await();
				System.out.println("消费了商品..."+this.name+"..."+this.num);
				flagLock = false;
				condition_producer.signal();
				}
			catch(InterruptedException interrupted)
			{
				System.out.println(interrupted.toString());
			}finally{
				lock.unlock();
			}
	}
}

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();
	}
}
分析:程序可以完美运行,需要参考者自己运行。
Javac 编译文件  java 运行文件即可



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