线程交互的应用
生产者-消费者问题是多线程数据同步的经典问题,请编程实现生产者、消费者和缓冲数据区域,并编写测试代码验证。
// 产品
public class Product {
public int id;
private String prodecuBy = "N/A";
private String consumeBy = "N/A";
// 产品ID,和生产者的名字
public Product(int id, String prodecuBy) {
this.id = id;
this.prodecuBy = prodecuBy;
}
public String getProdecuBy() {
return prodecuBy;
}
public void setProdecuBy(String prodecuBy) {
this.prodecuBy = prodecuBy;
}
public String getConsumeBy() {
return consumeBy;
}
public void setConsumeBy(String consumeBy) {
this.consumeBy = consumeBy;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", prodecuBy='" + prodecuBy + '\'' +
", consumeBy='" + consumeBy + '\'' +
'}';
}
}
// 存储产品
public class ProductStack {
public int index = 0;
public Product[] products = new Product[5];
//生产者放入
public synchronized void push(Product product){
// 等待,避免越界
while (index >= products.length){
System.out.println(product.getProdecuBy() + "is waiting!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 唤醒
System.out.println(product.getProdecuBy()+"send a notifyAll.");
notifyAll();
products[index] = product;
index++;
System.out.println(product.getProdecuBy()+"生产了"+product);
}
//消费者取出
public synchronized Product pop(String consumerName){
while (index == 0){
System.out.println(consumerName + "is waiting!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 唤醒等待的生产者
System.out.println(consumerName+"send a notifyAll.");
notifyAll();
index--;
Product product = products[index];
System.out.println(product.getConsumeBy()+"生产了"+product);
return product;
}
}
// 消费者、生产者线程创建、运行线程
class Producter implements Runnable{
private String name;
private ProductStack productStack = null;
public Producter(String name, ProductStack productStack) {
this.name = name;
this.productStack = productStack;
}
@Override
public void run() {
for (int i = 0; i < 10; i++){
Product product = new Product(i, name);
productStack.push(product);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private String name;
private ProductStack productStack;
public Consumer(String name, ProductStack productStack) {
this.name = name;
this.productStack = productStack;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Product product = productStack.pop(name);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
ProductStack productStack = new ProductStack();
Producter producter = new Producter("生产者:A ", productStack);
Consumer consumer = new Consumer("消费者:1", productStack);
new Thread(producter).start();
new Thread(consumer).start();
}
}
结果截图: