今天给大家分享一下一个经典的案例,供给他人学习以及自己今天的回首展望,首先让我们先看一下需求:
1.并行生成任务,id是唯一,不能重复
2.并行消费,id按照升序打印出来
3.精确任务到200个,并计算出消费时间
首先根据需求分析,我们首先来创建一个实体类,该实体类只有一个id属性,并提供get set方法和构造函数
public class Task {
private Integer id;
public Task(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
然后创建生产者和消费者的对应的接口
//生产者
public interface Prodeucer {
void produce() throws InterruptedException;
}
//消费者
public interface Consumer {
void consumer()throws InterruptedException;
}
根据最近所研究的模板模式,正好这个案例就将他实用上,创建生产者和消费者的接口实现类
//生产者接口实现类
public abstract class AbstaractProducer implements Prodeucer,Runnable {
@Override
public void run() {
while (true){
try {
produce();
}