- 商品类:
package com.pc;
public class Goods {
private final String id;
private final String name;
public Goods(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Goods{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
- 生产者类:
package com.pc;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
public class Producer implements Runnable {
private final Queue<Goods> queue;
private final Integer maxCapacity = 10;
private final AtomicInteger id = new AtomicInteger(0);
public Producer(Queue<Goods> queue) {
this.queue = queue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this.queue) {
if(queue.size() == maxCapacity) {
System.out.println(Thread.currentThread().getName() + "容器满了,等待消费");
try {
this.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Goods good = new Goods(String.valueOf(id.getAndIncrement()), "A商品");
System.out.println(Thread.currentThread().getName() + "生产商品" + good);
this.queue.add(good);
}
}
}
}
}
- 消费者类:
package com.pc;
import java.util.Queue;
public class Customer implements Runnable {
private final Queue<Goods> queue;
public Customer(Queue<Goods> queue) {
this.queue = queue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this.queue) {
if(this.queue.isEmpty()) {
System.out.println(Thread.currentThread().getName() + "容器已空,通知生产");
this.queue.notifyAll();
} else {
Goods good = this.queue.poll();
if(good != null) {
System.out.println(Thread.currentThread().getName() + "消费商品" + good);
}
}
}
}
}
}
- 测试类:
package com.pc;
import java.util.LinkedList;
import java.util.Queue;
public class TestProducerCustomer {
public static void main(String[] args) {
final Queue<Goods> queue = new LinkedList<>();
final Runnable producer = new Producer(queue);
final Runnable customer = new Customer(queue);
for(int i = 0; i < 5; i++) {
new Thread(producer, "Thread-producer-" + i).start();
}
for(int i = 0; i < 8; i++) {
new Thread(customer, "Thread-customer-" + i).start();
}
}
}