我的代码怎么运行不起来呢,纠结呐,是我打错哪里了吗- public class ProducerConsumerDemo {
- public static void mian(String args[]) {
- Resource r = new Resource();
- Producer pr = new Producer(r);
- Consumer co = new Consumer(r);
- new Thread(pr).start();
- new Thread(co).start();
- }
- }
- /*
- * 资源中心*/
- class Resource {
- private String name;
- private int count = 1;
- private boolean flag = false;
-
- //生产
- public synchronized void set(String name) {
- if(flag)
- try{this.wait();}catch(Exception e) {}
- this.name = name +"---"+count++;
- System.out.println(Thread.currentThread().getName()+"...生产..."+this.name);
- flag = false;
- this.notify();
- }
- //消费
- public synchronized void out() {
- if(!flag)
- try{this.wait();}catch(Exception e) {}
- System.out.println(Thread.currentThread().getName()+".......消费..."+this.name);
- flag = true;
- this.notify();
- }
- }
- //生产者
- class Producer implements Runnable {
- private Resource res;
- Producer(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- res.set("*面包*");
- }
- }
- //消费者
- class Consumer implements Runnable {
- private Resource res;
- Consumer(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- res.out();
- }
- }
复制代码
|