java 并发学习笔记(一)生产者消费者

package producer_consumer1;

import java.util.concurrent.*;

import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

/**
 * The produer-consumer approach task cooperation
 * @author wawa
 *
 */
public class Restaurant {
	
	Meal meal;
	ExecutorService executroService=Executors.newCachedThreadPool();
	WaitPerson waitor=new WaitPerson(this);
	Chef chef=new Chef(this);
	public Restaurant()
	{
		executroService.execute(chef);
		executroService.execute(waitor);
	}
	public static void main(String [] args)
	{
		new Restaurant();
	}
}

class Meal
{
	private final int orderNum;
	public Meal(int orderNum)
	{
		this.orderNum=orderNum;
	}
	public String toString()
	{
		return "Meal"+orderNum;
	}
}

class WaitPerson implements Runnable
{
	private Restaurant restaurant;
	
	public WaitPerson(Restaurant res)
	{
		this.restaurant=res;
	}
	public void run() {
		try {
			while(!Thread.interrupted())
			{
				synchronized (this) {
					while(restaurant.meal==null)
					{
						wait();// ...for the chef to produce a meal
					}
				}
				System.out.println("WaitPerson got "+restaurant.meal);
				synchronized (restaurant.chef) {
					restaurant.meal=null;
					restaurant.chef.notifyAll();  //Ready for another
				}
			}
		 }
	    catch (InterruptedException e) {
		// TODO Auto-generated catch block
		//e.printStackTrace();
		System.out.println("WaitPerson interrupted");
	    }
	}	
}
class Chef implements Runnable
{
	private Restaurant restaurant;
	private int count=0;
	public Chef(Restaurant res)
	{
		this.restaurant=res;
	}
	public void run() {
		try {
			while(!Thread.interrupted())
			{
					synchronized (this) {
						while(restaurant.meal!=null)
						{
							wait();// ...for the meal to taken
						}
					}
					if(++count==10)
					{
						System.out.println("Out of food, closing");
						restaurant.executroService.shutdownNow();
					}
					System.out.printf("Order up!");
					synchronized (restaurant.waitor) {
						restaurant.meal=new Meal(count);
						restaurant.waitor.notifyAll();
					}
					TimeUnit.MILLISECONDS.sleep(100);
			}
		}
	    catch (InterruptedException e) {
		//e.printStackTrace();
		System.out.println("chef interrupted");
	    }
	}
}

在chef中,调用shutdownNow()后,将向所有由ExecutorService启动的任务发送interrupt(),但在chef中,任务并没有在获得该interrupt()后立即关闭,因为当任务试图进入一个阻塞操作时,这个中断只能抛出InterrupedException。所有,先看到显示的是“Order up”,然后当chef试图调用sleep()时,抛出了InterrupedException。如果移除对sleep()的调用,那么这个任务将回到run()循环的顶部。并由于Thread.interrupted(),测试而退出,这是并不抛异常

你可能感兴趣的:(java,apache,thread,UP,sun)