一个生产者/一个消费者:

  

 /**
* 生产者
*/
public class P {
private MyStack stack; public P(MyStack stack) {
this.stack = stack;
} public void pushService() {
stack.push();
}
}
 /**
* 消费者
*/
public class C {
private MyStack stack; public C(MyStack stack) {
this.stack = stack;
} public void popService() {
System.out.println("pop = " + stack.pop());
}
}
 /**
* 生产者线程
*/
public class P_Thread extends Thread {
private P p; public P_Thread(P p) {
this.p = p;
} @Override
public void run() {
while (true) {
p.pushService();
}
}
}
 /**
* 消费者线程
*/
public class C_Thread extends Thread {
private C c; public C_Thread(C c) {
this.c = c;
} @Override
public void run() {
while (true) {
c.popService();
}
}
}
 /**
* 模拟栈List
*/
public class MyStack {
private List<Object> list = new ArrayList<>(); //压栈
public synchronized void push() {
try {
while(list.size() == 1) {
this.wait();
}
list.add(""+Math.random());
this.notify();
System.out.println("push:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
} //弹栈
public synchronized String pop() {
String value = "";
try {
while(list.size() == 0) {
this.wait();
}
value = ""+list.get(0);
list.remove(0);
this.notify();
System.out.println("pop:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
 /**
* 测试类
*/
public class Run { public static void main(String[] args) {
MyStack stack = new MyStack();
//创建生产和消费者
P p = new P(stack);
C c = new C(stack); //创建生产和消费者线程
P_Thread pThread = new P_Thread(p);
C_Thread cThread = new C_Thread(c); //启动
pThread.start();
cThread.start();
}
}

运行结果如下:

  生产者与消费者-1:1-基于list-LMLPHP

05-22 03:04