刚学线程 想实现简单的生产消费程序:
pppppppppppppppppppp
cccccccccccccccccccc
pppppppppppppppppppp
cccccccccccccccccccc
...
p是生产一次, c是消费一次
代码如下
- Java code
class Food{ static boolean flag = true; // 设 true 需要生产 public synchronized void proFood(){ if(!flag){ try{ super.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } try{ Thread.sleep(100); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("pppppppppp"); flag = false; super.notify(); } public synchronized void conFood(){ if(flag){ try{ super.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } try{ Thread.sleep(1); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("ccccccccc"); flag = true; super.notify(); }}class Producer implements Runnable{ Food f = new Food(); public static int howMany; Producer(int howMany){ this.howMany = howMany; } public void run(){ for(int i = 0; i < howMany; i++){ f.proFood(); } } }class Consumer implements Runnable{ Food f = new Food(); public void run(){ for(int i = 0; i < Producer.howMany; i++){ f.conFood(); } }}public class Test { public static void main(String args[]) throws Exception{ Producer p = new Producer(10); Consumer c = new Consumer(); new Thread(p).start(); new Thread(c).start(); }}
结果只输出了一行pppppppppppppp 就停住了,程序没有结束,好像哪里死锁了 ???
------解决方案--------------------
你创建的都是不同的Food对象,他们之间是无法通过wait()方法和notify()方法进行同步控制