Java基礎小記-多執行緒-生產者消費者-管程法(計數器)
阿新 • • 發佈:2020-12-15
技術標籤:Java
Java基礎小記-多執行緒-生產者消費者-管程法(計數器)
注意:
-
this.notifyAll(); this.wait(); //wait()會直接暫停在這,notifyAll()喚醒其他執行緒,得在wait()之前。
-
this.notifyAll(); //喚醒的是,呼叫notifyAll()方法所在的類的所有wait(WAITING狀態)的執行緒,使其從wait()方法處繼續執行。
程式碼示例:
package proud;
//多執行緒 多生產者 多消費者 管程計數
public class Test {
private static class Producer extends Thread {
private Store store;
public Producer(Store store, String name) {
super(name);
this.store = store;
}
@Override
public void run() {
store.make();
}
}
private static class Consumer extends Thread {
private Store store;
public Consumer(Store store, String name) {
super(name);
this.store = store;
}
@Override
public void run() {
store.eat();
}
}
private static class Store {
int count = 0;
public synchronized void make() {
while (true) {
try {
if (count <= 0) {
//生產
Thread.sleep(1000);
count += 3;
System.out.println(Thread.currentThread().getName() + "生產了3只雞");
}
//等待,通知消費者吃
this.notifyAll();
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void eat() {
while (true) {
try {
if (count > 0) {
//吃
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "吃了第" + count-- + "只雞");
}
//等待,通知生產
this.notifyAll();
System.out.println(Thread.currentThread().getName() + "進入wait");
this.wait();
System.out.println(Thread.currentThread().getName() + "wait後獲得鎖");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Store store = new Store();
new Producer(store, "生產者1------").start();
new Consumer(store, "消費者1--").start();
new Consumer(store, "消費者2--").start();
new Consumer(store, "消費者3--").start();
new Consumer(store, "消費者4--").start();
}
}
/*
執行結果:
生產者1------生產了3只雞
消費者4--吃了第3只雞
消費者4--進入wait
消費者3--吃了第2只雞
消費者3--進入wait
消費者2--吃了第1只雞
消費者2--進入wait
消費者1--進入wait
消費者2--wait後獲得鎖
消費者2--進入wait
消費者3--wait後獲得鎖
消費者3--進入wait
消費者4--wait後獲得鎖
消費者4--進入wait
生產者1------生產了3只雞
消費者4--wait後獲得鎖
消費者4--吃了第3只雞
消費者4--進入wait
消費者3--wait後獲得鎖
消費者3--吃了第2只雞
消費者3--進入wait
消費者2--wait後獲得鎖
消費者2--吃了第1只雞
消費者2--進入wait
消費者1--wait後獲得鎖
消費者1--進入wait
消費者2--wait後獲得鎖
消費者2--進入wait
消費者3--wait後獲得鎖
消費者3--進入wait
消費者4--wait後獲得鎖
消費者4--進入wait
*/