需求:要求倉庫最大容量為4,且一共只生產20臺電視機,下面的程式碼只適用於一個生產者一個消費者,有沒有大佬提點建議怎麼改成一對多或多對多不會出現死鎖情況
class Warehouse {
private int TVCount = 0;
// 生產
public synchronized void produce() {
if (TVCount < 4) {
TVCount++;
System.out.println(Thread.currentThread().getName() + "開始生產第 " + TVCount + " 臺電視");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.notify();
} else {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 消費
public synchronized void consume() {
if (TVCount > 0) {
System.out.println(Thread.currentThread().getName() + "開始消費第 " + TVCount + " 臺電視");
TVCount--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.notify();
} else {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Productor extends Thread {
private Warehouse warehouse;
public Productor(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
System.out.println("開始生產電視機");
for (int i = 0; i < 20; i++) {
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
warehouse.produce();
}
}
}
class Consumer extends Thread {
private Warehouse warehouse;
public Consumer(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
System.out.println("開始消費新產品");
for (int i = 0; i < 20; i++) {
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
warehouse.consume();
}
}
}
public class ThreadExer5 {
public static void main(String[] args) {
Warehouse warehouse = new Warehouse();
Productor t1 = new Productor(warehouse);
// Productor t3 = new Productor(warehouse);
Consumer t2 = new Consumer(warehouse);
t1.setName("生產者1");
t2.setName("消費者1");
// t3.setName("生產者2");
t1.start();
t2.start();
// t3.start();
}
}