多线程之生产者与消费者
2019-11-05 本文已影响0人
是我真的是我
Box
public class Box {
private int apple = 0;
public static void main(String[] args) {
Box box = new Box();
Thread product = new Thread(new Product(box), "生产者1");
Thread consumer = new Thread(new Consumer(box), "消费者1");
Thread consumer2 = new Thread(new Consumer(box), "消费者2");
product.start();
consumer.start();
consumer2.start();
}
public synchronized void add(){
while (apple == 5){
try {
wait();
}catch (Exception e){
}
}
apple ++;
System.out.println("生产苹果成功");
notifyAll();
}
public synchronized void put(){
while (apple == 0){
try {
wait();
}catch (Exception e){
}
}
apple --;
notifyAll();
}
}
Product
public class Product implements Runnable {
Box box;
public Product(Box b){
box = b;
}
@Override
public void run(){
for (int i=0; i<10; i++){
try {
box.add();
int rt = (int)(Math.random() * 100);
Thread.sleep(rt + 100);
}catch (Exception e){
}
}
}
}
Consumer
package Thread;
public class Consumer implements Runnable {
Box box;
public Consumer(Box b){
box = b;
}
@Override
public void run(){
for (int i=0; i<5; i++){
try {
box.put();
System.out.println(Thread.currentThread().getName() + "吃了一个苹果");
int rt = (int)(Math.random() * 100);
Thread.sleep(rt + 400);
}catch (Exception e){
}
}
}
}
运行结果展示