最简单的多线程问题
使用sychronized
生产者
public class Producer implements Runnable{
private Goods goods;
public Producer(Goods goods) {
this.goods=goods;
}
@Override
public void run() {
for (int i = 0; i < 25; i++) {
goods.make("旺仔","小馒头");
}
}
}
消费者
public class Consumer implements Runnable{
private Goods goods;
public Consumer(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
goods.sell("旺仔","小馒头");
}
}
}
商品
public class Goods {
private int quantity;// 库存
private String brand;
private String name;
public Goods() {
}
public Goods( String brand, String name) {
this.brand = brand;
this.name = name;
}
// 消费商品
public synchronized void sell(String brand,String name) {
if (quantity == 0){// 库存没了等待生产
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
quantity--;
System.out.println("消费了"+brand+name + "--现在库存"+quantity);
notify(); // 唤醒
}
// 生产商品
public synchronized void make(String brand,String name) {
if (quantity == 10){// 仓库满了,等待销售
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
quantity++;
System.out.println("生产了"+brand+name + "--现在库存"+quantity);
notify(); // 唤醒
}
@Override
public String toString() {
return "Goods{" +
"quantity=" + quantity +
", brand='" + brand + '\'' +
", name='" + name + '\'' +
'}';
}
}
测试类
Goods goods =new Goods();
Producer producer=new Producer(goods);
Consumer consumer = new Consumer(goods);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t2.start();
t1.start();
使用JUC包中的 BlockingQueue
生产者
public class ProducerQueue implements Runnable{
private BlockingQueue<Goods> blockingQueue;
public ProducerQueue(BlockingQueue<Goods> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Goods goods = new Goods("wahaha","矿泉书");
System.out.println("生产者生产商品" + goods);
try {
blockingQueue.put(goods);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
public class ConsumerQueue implements Runnable {
private BlockingQueue<Goods> blockingQueue;
public ConsumerQueue(BlockingQueue<Goods> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Goods goods = blockingQueue.take();
System.out.println("消费者消费商品" + goods);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
Goods goods =new Goods();
BlockingQueue<Goods> queue = new ArrayBlockingQueue<>(5);
ProducerQueue producerQueue = new ProducerQueue(queue);
ConsumerQueue consumerQueue = new ConsumerQueue(queue);
Thread t1 = new Thread(consumerQueue);
Thread t2 = new Thread(producerQueue);
t1.start();
t2.start();