2012-06-27 58 views
-2

以下源代码用于实现产品/消费者模式,但它们效果不佳,我不知道如何解决它。关于消费者/产品模式

类1:生产方

package test; 

import java.util.ArrayList; 
import java.util.List; 

public class Productor extends Thread { 

private List list = null; 

public Productor(ArrayList list) { 
    this.list = list; 
} 

public synchronized void product() throws InterruptedException { 
    for (int e = 0; e < 10; e++) { 
     System.out.println("Add-" + e + " " + System.currentTimeMillis()); 
     list.add(e); 

     if (list.size() >= 10) { 
      wait(); 
     } else { 
      notifyAll(); 
     } 
    } 
} 

public void run() { 
    try { 
     while(true){ 
      product(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

类2:消费者 封装测试;

import java.util.ArrayList; 
import java.util.List; 

public class Consumer extends Thread { 

private List list = null; 

public Consumer(ArrayList list) { 
    this.list = list; 
} 

public synchronized void consume() throws InterruptedException { 
    if (list.size() <= 0) { 
     wait(); 
    } else { 
     notifyAll(); 
    } 

    for (int e = 0; e < list.size(); e++) { 
     System.out.println("Remove-" + e + " " 
       + System.currentTimeMillis()); 
     list.remove(e); 
    } 
} 

public void run() { 
    try { 
     while(true){ 
      consume(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

} 

类3:测试的产品/消费者 封装测试;

import java.util.ArrayList; 

public class TestCP { 
public static void main(String args[]) throws InterruptedException { 
    ArrayList product = new ArrayList(); 
    Productor pt = new Productor(product); 
    Consumer ct = new Consumer(product); 
    pt.start(); 
    ct.start(); 
} 
} 

TestCP的输出是:

添加-0 1340777963967

添加-1 1340777963968

添加-2 1340777963968

添加-3 1340777963968

添加-4 1340777963968

添加-5- 1340777963968

添加-6- 1340777963968

添加-7 1340777963968

添加-8 1340777963968

添加-9 1340777963968

我的意图是,生产方的产品10元素存储在列表中并由消费者使用,然后Productor产品元素再次消费,消费者再次消费... 任何反馈将b e表示感谢,谢谢。

+3

如果你说他们做得不好,他们应该做什么,以及你已经试图解决这个问题,这可能会有所帮助。 “他们工作不好”对我们无益。 – Eric

+2

你能比“不好工作”更具体吗?你更有可能通过更好的措辞问题得到高质量的答案。 – 2012-06-27 06:15:58

+1

你想做什么,你得到什么? –

回答

0

您等待/通知不在列表中的不同线程。所以线程在自己的显示器上运行,而不是共享的。搜索“java等待通知”并继续阅读。