日期:2014-05-20 浏览次数:20649 次
class ProductorConsumer { public static void main( String args[] ) { Resource res=new Resource();// 创建共享资源 new Thread( new Productor(res) ).start(); new Thread( new Productor(res) ).start(); new Thread( new Consumer(res) ).start(); new Thread( new Consumer(res) ).start(); } } class Resource { private int account=0; private boolean flag=false; public boolean getFlag() { return flag; } public void setFlag(boolean a) { flag=a; } public void product() { account++; System.out.println(Thread.currentThread().getName()+"生产"+account); } public void pay() { System.out.println("\t\t\t"+Thread.currentThread().getName()+"消费"+account); } } class Productor implements Runnable { private Resource res; Productor(Resource res) { this.res=res; } public void run() { synchronized(res) { while(res.getFlag()) try { this.wait(); } catch (Exception e) { System.out.println("error"); } res.product(); res.setFlag(true); this.notifyAll(); } } } class Consumer implements Runnable { private Resource res; Consumer( Resource res ) { this.res=res; } public void run() { synchronized(res) { while(!res.getFlag()) try { this.wait(); } catch ( Exception e ) { System.out.println("error"); } res.pay(); res.setFlag(false); this.notifyAll(); } } }