生產者與消費者案例
阿新 • • 發佈:2022-03-31
package Thread.summary;
/**
* FileName: Boxdemo
* Author: lps
* Date: 2022/3/31 15:33
* Sign:劉品水 Q:1944900433
*/
public class Boxdemo {
public static void main(String[] args) {
Box b = new Box();
Producer p = new Producer(b);
Customer c = new Customer(b);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
package Thread.summary;
/**
* FileName: Box
* Author: lps
* Date: 2022/3/31 15:31
* Sign:劉品水 Q:1944900433
*/
public class Box {
private int milk;
//定義一個成員變量表示奶箱狀態
private boolean state = false;
public synchronized void put(int milk) {
if (state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.milk = milk;
System.out.println("送奶大哥將第" + this.milk + "瓶奶放入了奶箱");
state = true;
notifyAll();
}
public synchronized void get() {
if (!state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("喝奶小老弟將第" + this.milk + "瓶奶從奶箱取出");
state = false;
notifyAll();
}
}
package Thread.summary;
/**
* FileName: Producer
* Author: lps
* Date: 2022/3/31 15:31
* Sign:劉品水 Q:1944900433
*/
public class Producer implements Runnable{
private Box b;
public Producer(Box b) {
this.b=b;
}
@Override
public void run() {
for (int i = 1; i <=10 ; i++) {
b.put(i);
}
}
}
package Thread.summary;
/**
* FileName: Customer
* Author: lps
* Date: 2022/3/31 15:31
* Sign:劉品水 Q:1944900433
*/
public class Customer implements Runnable{
private Box b;
public Customer(Box b) {
this.b=b;
}
@Override
public void run() {
while (true){
b.get();
}
}
}