今天看生产者与消费者!写的代码,不知道错在哪里。- class Shop
- {
- private String name;
- private int num = 1;
- private boolean flag = false;
- public synchronized void pro(String name)
- {
- if(flag)
- try{wait();}catch(Exception e){}
-
- this.name = name+"----"+num++;
- System.out.println(Thread.currentThread().getName()+"生产--"+name);
-
- flag = true;
-
- notifyAll();
- }
- public synchronized void con()
- {
- if(!flag)
- try{wait();}catch(Exception e){}
-
- System.out.println(Thread.currentThread().getName()+"消费------"+name);
-
- flag = false;
-
- notifyAll();
- }
- }
- class Pro implements Runnable
- {
- private Shop s;
- Pro(Shop s)
- {
- this.s = s;
- }
- public void run()
- {
- while(true)
- s.pro("娃娃");
- }
- }
- class Con implements Runnable
- {
- private Shop s;
- Con(Shop s)
- {
- this.s = s;
- }
- public void run()
- {
- while(true)
- s.con();
- }
- }
- class ProConTest
- {
- public static void main(String[] args)
- {
- Shop s = new Shop();
- Pro p = new Pro(s);
- Con c = new Con(s);
- Thread t1 = new Thread(p);
- Thread t2 = new Thread(c);
- t1.start();
- t2.start();
- }
- }
复制代码
|