生产者和消费者模式.
核心是生产者(1-n)个和消费者(1-n)个,共同使用同一个队列对象,通过多线程的同步机制等.同一个时间,只有一个生产者或者消费者能向该队列写入消息,或者取出消息(互斥锁)
package com.hgh.java_duoxiancheng.ch3_1.p11;
import java.util.ArrayList;
import java.util.List;
public class MyList {
public List<String> list = new ArrayList<String>();
synchronized void push(){
try {
while (list.size() == 1 ) {
this.wait();
}
list.add("andy string = " + Math.random());
this.notify();
System.out.println("pusg=" + list.size());
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized String pop(){
String value = "";
try {
while (list.size() == 0 ) {
System.out.println("pop " + Thread.currentThread().getName() + " wait");
this.wait();
}
value = list.get(0);
list.remove(0);
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
package com.hgh.java_duoxiancheng.ch3_1.p11;
public class P {
private MyList list;
P(MyList list){
this.list = list;
}
public void pushService(){
list.push();
}
}
package com.hgh.java_duoxiancheng.ch3_1.p11;
public class C {
private MyList list;
C(MyList list){
this.list = list;
}
public void popService(){
list.pop();
}
}
package com.hgh.java_duoxiancheng.ch3_1.p11;
public class ThreadP extends Thread{
private P p;
ThreadP(P p){
this.p = p;
}
@Override
public void run() {
while (true) {
p.pushService();
}
}
}
package com.hgh.java_duoxiancheng.ch3_1.p11;
public class ThreadC extends Thread{
private C c;
ThreadC(C c){
this.c = c;
}
@Override
public void run() {
while (true) {
c.popService();
}
}
}
package com.hgh.java_duoxiancheng.ch3_1.p11;
public class Run {
/**
* 验证生成者和消费者的模式
*
* @param args
*/
public static void main(String[] args) {
MyList myList = new MyList();
P p = new P(myList);
C c = new C(myList);
ThreadC threadC = new ThreadC(c);
ThreadP threadP = new ThreadP(p);
threadP.setName("P");
threadP.start();
threadC.setName("C");
threadC.start();
}
}