static class MangoIce{
int counter;
public MangoIce(int counter) {
this.counter = counter;
}
}
static class Producer implements Runnable
{
private final List<MangoIce> barCounter;
private final int MAX_CAPACITY;
public Producer(List<MangoIce> sharedQueue, int size)
{
this.barCounter = sharedQueue;
this.MAX_CAPACITY = size;
}
@Override
public void run()
{
int counter = 1;
while (!Thread.currentThread().isInterrupted())
{
try
{
produce(counter++);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
break;
}
}
}
private void produce(int i) throws InterruptedException
{
synchronized (barCounter)
{
while (barCounter.size() == MAX_CAPACITY)
{
System.out.println("吧檯滿了,冰沙放不下 " + Thread.currentThread().getName() + " 線程等待,當前吧檯冰沙數: " + barCounter.size());
barCounter.wait();
}
Thread.sleep(1000);
barCounter.add(new MangoIce(i));
System.out.println("生產第: " + i + "杯冰沙...");
barCounter.notifyAll();
}
}
}
static class Consumer implements Runnable
{
private final List<MangoIce> barCounter;
public Consumer(List<MangoIce> sharedQueue)
{
this.barCounter = sharedQueue;
}
@Override
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
try
{
consume();
} catch (InterruptedException ex)
{
ex.printStackTrace();
break;
}
}
}
private void consume() throws InterruptedException
{
synchronized (barCounter)
{
while (barCounter.isEmpty())
{
System.out.println("吧檯空的,沒有冰沙 " + Thread.currentThread().getName() + " 消費者線程等待,當前吧檯冰沙數: " + barCounter.size());
barCounter.wait();
}
Thread.sleep(1000);
MangoIce i = barCounter.remove(0);
System.out.println("消費第: " + i.counter + "杯冰沙...");
barCounter.notifyAll();
}
}
}
public static void main(String[] args)
{
List<MangoIce> taskQueue = new ArrayList<>();
int MAX_CAPACITY = 5;
Thread tProducer = new Thread(new Producer(taskQueue, MAX_CAPACITY), "生產者");
Thread tConsumer = new Thread(new Consumer(taskQueue), "消費者");
tProducer.start();
tConsumer.start();
}
控制檯輸出:
生產第: 1杯冰沙...
生產第: 2杯冰沙...
生產第: 3杯冰沙...
生產第: 4杯冰沙...
生產第: 5杯冰沙...
吧檯滿了,冰沙放不下 生產者 線程等待,當前吧檯冰沙數: 5
消費第: 1杯冰沙...
消費第: 2杯冰沙...
消費第: 3杯冰沙...
消費第: 4杯冰沙...
消費第: 5杯冰沙...
吧檯空的,沒有冰沙 消費者 消費者線程等待,當前吧檯冰沙數: 0
生產第: 6杯冰沙...
生產第: 7杯冰沙...
生產第: 8杯冰沙...
生產第: 9杯冰沙...
生產第: 10杯冰沙...
吧檯滿了,冰沙放不下 生產者 線程等待,當前吧檯冰沙數: 5
消費第: 6杯冰沙...
消費第: 7杯冰沙...