import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author zhenlong
* @version $Id: PC.java, v 0.1 2020年05月11日 12:48 AM zhenlong Exp $
*/
public class PC {
public static void main(String[] args) {
Resource resource = new Resource(10);
//生产者线程
ProducerThread p1 = new ProducerThread(resource, "生产者1号");
ProducerThread p2 = new ProducerThread(resource, "生产者2号");
ProducerThread p3 = new ProducerThread(resource, "生产者3号");
//消费者线程
ConsumerThread c1 = new ConsumerThread(resource, "消费者1号");
//ConsumerThread c2 = new ConsumerThread(resource);
//ConsumerThread c3 = new ConsumerThread(resource);
p1.start();
p2.start();
p3.start();
c1.start();
//c2.start();
//c3.start();
}
// 公共资源类
static class Resource {
// 锁
private final Object lock;
// 当前数量
private List<String> taskList;
// 任务上限
private int capacity;
public Resource(int capacity) {
this.capacity = capacity;
this.taskList = new ArrayList<>();
this.lock = new Object();
}
public void consume() throws Exception {
synchronized (lock) {
if (taskList.size() > 0) {
String task = taskList.remove(0);
System.out.println(Thread.currentThread().getName() +
"处理任务:" + task + "完成,当前池中任务数量:" + taskList.size());
//通知生产者生产资源
lock.notifyAll();
} else {
//如果没有资源,则消费者进入等待状态
System.out.println(Thread.currentThread().getName() + "线程进入等待");
lock.wait();
}
}
}
/**
* 向资源池中添加资源
*/
public void produce() throws Exception {
synchronized (lock) {
if (taskList.size() < capacity) {
taskList.add(UUID.randomUUID().toString());
System.out.println(Thread.currentThread().getName()
+ "生成任务,当前池中任务数量:" + taskList.size());
//通知等待的消费者
lock.notifyAll();
} else {
// 队列已满计入等到
System.out.println(Thread.currentThread().getName() + "线程进入等待");
lock.wait();
}
}
}
}
// 消费者线程
static class ConsumerThread extends Thread {
private Resource resource;
public ConsumerThread(Resource resource, String name) {
this.resource = resource;
super.setName(name);
}
@Override
public void run() {
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000));
resource.consume();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 生产者线程
static class ProducerThread extends Thread {
private Resource resource;
public ProducerThread(Resource resource, String name) {
this.resource = resource;
super.setName(name);
}
@Override
public void run() {
//不断地生产资源
while (true) {
try {
Thread.sleep((long) (Math.random() * 1000));
resource.produce();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}