public class MultiThread {
public static void main(String[] args) {
ProductStack box = new ProductStack("box");
Producer p1 = new Producer(box, "p1");
Producer p2 = new Producer(box, "p2");
Producer p3 = new Producer(box, "p3");
Consumer c1 = new Consumer(box, "c1");
Consumer c2 = new Consumer(box, "c2");
//Consumer c3=new Consumer(box,"c3");
//Consumer c4=new Consumer(box,"c4");
//Consumer c5=new Consumer(box,"c5");
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
//c3.start();
//c4.start();
// c5.start();
}
}
class Product {
int id;
public Product(int id) {
this.id = id;
}
public String toSring() {
return "Product" + id;
}
}
class ProductStack {
String name;
static int point = 0;
private Product[] p = new Product[10];
public ProductStack(String name) {
this.name = name;
}
public String getname() {
return name;
}
public synchronized int getpoint() {
return point;
}
public synchronized void push(Product a) {
while (point >= p.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.notifyAll();
}
p[point] = a;
// System.out.println(point);
// System.out.println(p[point].toSring());
point++;
// yield();
}
private void yield() {
}
public synchronized Product pop() {
while (point == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.notifyAll();
}
point--;
// System.out.println(point);
// Product get=p[point];
// System.out.println(p[point].toSring());
// yield();
return p[point];
}
}
class Producer extends Thread {
private ProductStack container = new ProductStack("container");
public Producer(ProductStack s, String name) {
super(name);
container = s;
}
public void run() {
Product m = new Product(0);
for (int i = 0; i < 20; i++) {
synchronized (container) {
m.id = container.getpoint() + 1;
container.push(m);
System.out.println(currentThread().getName() + " 生产了 "
+ m.toSring());
// }
try {
Thread.sleep((int) (Math.random() * 2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Consumer extends Thread {
private ProductStack container = new ProductStack("container");
public Consumer(ProductStack s, String name) {
super(name);
container = s;
}
public void run() {
Product n = new Product(0);
for (int j = 0; j < 20; j++) {
synchronized (container) {
n = container.pop();
System.out.println(currentThread().getName() + " 消耗了 "
+ n.toSring());
// }
yield();
try {
Thread.sleep((int) (Math.random() * 2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}