Basket类:生产者消费者需要互斥访问的资源
class Basket {
int capacity;
int num;
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
Basket(int capacity) {
this.capacity = capacity;
}
void put() {
lock.lock();
try {
while (num == capacity)
notFull.await();
num++;
System.out.println(Thread.currentThread().getName() + "生产一个面包,现在已有" + getNum() + "个面包");
notEmpty.signal();
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
void get() {
lock.lock();
try {
while (num == 0)
notEmpty.await();
num--;
System.out.println(Thread.currentThread().getName() + "消费一个面包!!!!!!!!!!!!!!!!!!!!!!!现在还剩" +
getNum() + "个面包");
notFull.signal();
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
int getNum() {
return num;
}
}
Producer类:生产者
class Producer implements Runnable {
Basket basket;
Producer(Basket basket) {
this.basket = basket;
}
@Override
public void run() {
while (true) {
basket.put();
try {
Thread.sleep(Math.round(1000 * Math.random()));
} catch (InterruptedException e) {
}
}
}
}
Consumer类:消费者
class Consumer implements Runnable {
Basket basket;
int demand;
Consumer(Basket basket, int demand) {
this.basket = basket;
this.demand = demand;
}
@Override
public void run() {
int demand = this.demand;
while (true) {
basket.get();
if (--demand == 0) {
System.out.println(Thread.currentThread().getName() + "吃了" + this.demand + "个面包吃饱了,溜溜球~~~~~~");
break;
}
try {
Thread.sleep(Math.round(2000 * Math.random()));
} catch (InterruptedException e) {
}
}
}
}
main方法:
public static void main(String[] args) {
Basket basket = new Basket(10);
Thread[] p = new Thread[2];
Thread[] c = new Thread[10];
for (int i = 0; i < p.length; i++) {
p[i] = new Thread(new Producer(basket), "生产者" + (i + 1) + "号");
p[i].setDaemon(true);
p[i].start();
}
for (int i = 0; i < c.length; i++) {
c[i] = new Thread(new Consumer(basket, (int) Math.ceil(5 * Math.random())),
"消费者" + (i + 1) + "号");
c[i].start();
}
}