1.ReentrantLock和Condition网上很多都有,我就不多介绍啦
2.具体实现见如下代码
控制台信息
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerAndCustomer {
private int count;
public final int MAX_COUNT = 10;
ReentrantLock reentrantLock = new ReentrantLock();
Condition push = reentrantLock.newCondition();
Condition take = reentrantLock.newCondition();
public void push() {
reentrantLock.lock();
while (count >= 10) try {
System.out.println("库存大于等于10个,阻塞停止生产!");
push.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println(Thread.currentThread().getName() + "生产者生产,库存:" + count);
take.signal();
reentrantLock.unlock();
}
public void take() {
reentrantLock.lock();
while (count <= 0) {
try {
System.out.println("拿的太快啦,收手停止一下啦!");
take.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println("有人偷偷拿走一个商品,还剩:" + count);
push.signal();
reentrantLock.unlock();
}
public static void main(String[] args) {
ProducerAndCustomer producerAndCustomer = new ProducerAndCustomer();
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Producer(producerAndCustomer));
executorService.execute(new Producer(producerAndCustomer));
executorService.execute(new Producer(producerAndCustomer));
executorService.execute(new Producer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
executorService.execute(new Customer(producerAndCustomer));
}
}
class Producer implements Runnable {
private ProducerAndCustomer producerAndCustomer;
public Producer(ProducerAndCustomer producerAndCustomer) {
this.producerAndCustomer = producerAndCustomer;
}
@Override
public void run() {
while (true) {
producerAndCustomer.push();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer implements Runnable {
private ProducerAndCustomer producerAndCustomer;
public Customer(ProducerAndCustomer producerAndCustomer) {
this.producerAndCustomer = producerAndCustomer;
}
@Override
public void run() {
while (true) {
producerAndCustomer.take();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
网友评论