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