生產者消費者模式(多執行緒)
阿新 • • 發佈:2021-02-08
Box
package com.d;
public class Box {
private int milk;
private boolean state=false;
public synchronized void put(int milk){
if(!state){
this.milk=milk;
System.out.println("師傅送來了第"+this.milk+"瓶奶");
state=true ;
notifyAll();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void get(){
if (state){
System.out.println("程式設計師拿到了第"+this.milk+"瓶奶");
state= false;
notifyAll();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Producer
package com.d;
public class Producer implements Runnable{
private Box b;
public Producer(Box b) {
this .b=b;
}
@Override
public void run() {
for (int i = 1; i <6; i++) {
b.put(i);
}
}
}
Costomer
package com.d;
public class Customer implements Runnable{
private Box b;
public Customer(Box b) {
this.b=b;
}
@Override
public void run() {
while(true) {
b.get();
}
}
}
ThreadDemo
package com.d;
public class ThreadDemo {
public static void main(String[] args) {
Box b=new Box();//物件
Producer producer = new Producer(b);//動作
Customer customer = new Customer(b);//動作
Thread thread = new Thread(producer);//進行動作
Thread thread1 = new Thread(customer);//進行動作
thread.start();
thread1.start();
}
}