本帖最后由 rolan 于 2015-4-29 22:47 编辑
关于生产者模式,我写的代码和老师的一样,为什么会有这么多错误啊?求指导- class ProducerConsumerDemo{
- public static void main(String[] args){
- Resource re=new Resource();
- Producer pro=new Producer(re);
- Consumer con=new Consumer(re);
- Thread t1=new Thread(pro);
- Thread t2=new Thread(con);
- t1.start();
- t2.start();
- }
- }
- class Resource{
- private String name;
- private int count=1;
- boolean flag=false;
- public synchronized void set(String name){
- if(flag){
- try{
- wait();
- }catch(Exception e){
- }
- }
- this.name=name+"-------"+count++;
- System.out.println("-----生产者------"+Thread.currentThread().getName()+name);
- flag=true;
- notify();
- }
- public synchronized void out(){
- if(!flag){
- try{wait();
- }catch(Exception e){
- }
- }
- System.out.println("-----消费者------"+Thread.currentThread().getName()+name);
- flag=false;
- notify();
- }
- }
- class Producer implements Runnable{
- private Resource res;
- Producer(Resource res){
- this.res=res;}
- public void run(){
- while(true){
- re.set("商品");
-
- }
- }
- }
- class Consumer implements Runnable{
- private Resource res;
- Consumer(Resource res){
- this.res=res;}
- public void run(){
- while(true){
- re.out();
-
- }
- }
- }
复制代码 |
|