日期:2014-05-20 浏览次数:20697 次
class ProductorConsumer { public static void main( String args[] ) { Resource res=new Resource();// 创建共享资源 new Thread( new Productor(res) ).start(); new Thread( new Consumer(res) ).start(); } } class Resource { private int account=0; private boolean flag=false; 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 synchronized void run() { while(res.flag) try { wait(); } catch (Exception e) { System.out.println("error"); } res.product(); res.flag=true; this.notifyAll(); } } class Consumer implements Runnable { private Resource res; Consumer( Resource res ) { this.res=res; } public synchronized void run() { while(!res.flag) try { wait(); } catch ( Exception e ) { System.out.println("error"); } res.pay(); res.flag=false; this.notifyAll(); } }