package com.wz.thread.cp;
import java.util.ArrayList;
import java.util.List;
/**
* 商品类(仓库中只能存放一个商品)
* @author Administrator
*
*/
public class MyStack {
private List list = new ArrayList();
synchronized public void push() {
try {
// 因为等待wait的条件在改变,使用if判断容易造成程序逻辑的混乱,所以使用while循环
while(list.size() == 1) {
this.wait();
}
list.add("anyString=" + Math.random());
this.notifyAll();
System.out.println("push=" + list.size());
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized public String pop() {
String returnValue = "";
try {
while(list.size() == 0) {
System.out.println("pop操作中的:" + Thread.currentThread().getName() + "线程呈wait状态");
this.wait();
}
returnValue = "" + list.get(0);
list.remove(0);
this.notifyAll();
System.out.println("pop=" + list.size());
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
}
package com.wz.thread.cp;
/**
* 生产者
* @author Administrator
*
*/
public class P{
private MyStack stack = new MyStack();
public P(MyStack stack) {
super();
this.stack = stack;
}
public void pushService() {
stack.push();
}
}
package com.wz.thread.cp;
/**
* 消费者
* @author Administrator
*
*/
public class C{
private MyStack stack = new MyStack();
public C(MyStack stack) {
super();
this.stack = stack;
}
public void popService() {
System.out.println("pop=" + stack.pop());
}
}
package com.wz.thread.cp;
/**
* 生产者线程
* @author Administrator
*
*/
public class ThreadP extends Thread{
private P p;
public ThreadP(P p) {
super();
this.p = p;
}
@Override
public void run() {
super.run();
p.pushService();
}
}
package com.wz.thread.cp;
/**
* 消费者线程
* @author Administrator
*
*/
public class ThreadC extends Thread{
private C c;
public ThreadC(C c) {
super();
this.c = c;
}
@Override
public void run() {
super.run();
c.popService();
}
}
package com.wz.thread.cp;
/**
* 测试主方法(有输出结果可以看出list.size()没有超过1)
* @author Administrator
*
*/
public class Run {
public static void main(String[] args) {
MyStack stack = new MyStack();
P p1 = new P(stack);
P p2 = new P(stack);
P p3 = new P(stack);
P p4 = new P(stack);
P p5 = new P(stack);
P p6 = new P(stack);
ThreadP tp1 = new ThreadP(p1);
ThreadP tp2 = new ThreadP(p2);
ThreadP tp3 = new ThreadP(p3);
ThreadP tp4 = new ThreadP(p4);
ThreadP tp5 = new ThreadP(p5);
ThreadP tp6 = new ThreadP(p6);
tp1.start();
tp2.start();
tp3.start();
tp4.start();
tp5.start();
tp6.start();
C c1 = new C(stack);
C c2 = new C(stack);
C c3 = new C(stack);
C c4 = new C(stack);
C c5 = new C(stack);
C c6 = new C(stack);
ThreadC tc1 = new ThreadC(c1);
ThreadC tc2 = new ThreadC(c2);
ThreadC tc3 = new ThreadC(c3);
ThreadC tc4 = new ThreadC(c4);
ThreadC tc5 = new ThreadC(c5);
ThreadC tc6 = new ThreadC(c6);
tc1.start();
tc2.start();
tc3.start();
tc4.start();
tc5.start();
tc6.start();
}
}