package com.phj20110824.bread;
class Warehouse {
private static int num = 0;
public synchronized void product() {
while (this.getNum() == 2) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num++;
System.out.println(this.getNum());
notify();
}
public synchronized void customer() {
while (this.getNum() == 1) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num--;
System.out.println(this.getNum());
notify();
}
public int getNum() {
return this.num;
}
}
class ProduceThread implements Runnable {
private Warehouse warehouse;
public ProduceThread(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
warehouse.product();
}
}
}
class CustomerThread implements Runnable {
private Warehouse warehouse;
public CustomerThread(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
warehouse.customer();
}
}
}
public class ProduceCustomerDemo {
public static void main(String[] args) {
Warehouse warehouse = new Warehouse();
new Thread(new ProduceThread(warehouse)).start();
new Thread(new CustomerThread(warehouse)).start();
new Thread(new ProduceThread(warehouse)).start();
new Thread(new CustomerThread(warehouse)).start();
new Thread(new ProduceThread(warehouse)).start();
new Thread(new CustomerThread(warehouse)).start();
}
}
多線程producer&customer
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.