用JAVA中的多线程示例生产者和消费者问题
package com.softeem.demo;
class Producer implements Runnable {
private SyncStack stack;
public Producer(SyncStack stack) {
this.stack = stack;
}
public void run() {
for (int i = 0; i < stack.getProducts().length; i++) {
String product = "产品" + i;
stack.push(product);
System.out.println("生产了: " + product);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private SyncStack stack;
public Consumer(SyncStack stack) {
this.stack = stack;
}
public void run() {
for (int i = 0; i < stack.getProducts().length; i++) {
String product = stack.pop();
System.out.println("消费了: " + product);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SyncStack {
private String[] products = new String[10];
private int index;
public synchronized void push(String product) {
if (index == product.length()) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
products[index] = product;
index++;
}
public synchronized String pop() {
if (index == 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
index--;
String product = products[index];
return product;
}
public String[] getProducts() {
return products;
}
}
public class TestProducerConsumer {
public static void main(String[] args) {
SyncStack stack = new SyncStack();
Producer p = new Producer(stack);
Consumer c = new Consumer(stack);
new Thread(p).start();
new Thread(c).start();
}
}