使用java 开发一个使用java 开发一个数据多线程数据拼接业务,一个实体类 有4个属性 id,param,no,num等 ,id是唯一标识符,param是拼接数据,no是用于排序,num是同一id下数据总数,业务需求是根据id判断是否同一个拼接的数据,然后将根据num判断接收的数据是否完整,如果拼接param,如果不是则放入缓存,保证线程安全及处理速度写出相应设计及代码数据多线程数据拼接业务,一个实体类 有4个属性 id,param,no,num等 ,id是唯一标识符,param是拼接数据,no是用于排序,num是同一id下数据总数,业务需求是根据id判断是否同一个拼接的数据,然后将根据num判断接收的数据是否完整,如果是则根据no进行排序然后拼接param,如果不是则放入缓存,写出相应设计及代码
时间: 2024-03-11 22:49:33 浏览: 77
设计思路:
1. 定义一个实体类,包含4个属性id、param、no、num;
2. 定义一个缓存类,用于存储未完整拼接的数据;
3. 定义一个拼接类,用于拼接完整数据并排序;
4. 定义多线程类,用于处理数据拼接业务。
代码实现:
1. 实体类
```
public class Data {
private String id;
private String param;
private int no;
private int num;
public Data(String id, String param, int no, int num) {
this.id = id;
this.param = param;
this.no = no;
this.num = num;
}
// getter and setter
}
```
2. 缓存类
```
public class Cache {
private Map<String, List<Data>> cacheMap = new ConcurrentHashMap<>();
public void addData(Data data) {
if (cacheMap.containsKey(data.getId())) {
List<Data> dataList = cacheMap.get(data.getId());
int size = dataList.size();
if (size < data.getNum()) {
dataList.add(data);
} else if (size == data.getNum()) {
dataList.add(data);
Collections.sort(dataList, Comparator.comparingInt(Data::getNo));
StringBuilder sb = new StringBuilder();
for (Data d : dataList) {
sb.append(d.getParam());
}
System.out.println("完整数据:" + sb.toString());
cacheMap.remove(data.getId());
}
} else {
List<Data> dataList = new ArrayList<>();
dataList.add(data);
cacheMap.put(data.getId(), dataList);
}
}
}
```
3. 拼接类
```
public class Joiner {
public static String joinData(List<Data> dataList) {
Collections.sort(dataList, Comparator.comparingInt(Data::getNo));
StringBuilder sb = new StringBuilder();
for (Data d : dataList) {
sb.append(d.getParam());
}
return sb.toString();
}
}
```
4. 多线程类
```
public class MultiThreadJoiner implements Runnable {
private Data data;
private Cache cache;
public MultiThreadJoiner(Data data, Cache cache) {
this.data = data;
this.cache = cache;
}
@Override
public void run() {
cache.addData(data);
}
}
```
测试代码:
```
public static void main(String[] args) {
Cache cache = new Cache();
// 模拟数据
Data data1 = new Data("1", "a", 1, 2);
Data data2 = new Data("1", "b", 2, 2);
Data data3 = new Data("2", "c", 1, 3);
Data data4 = new Data("2", "d", 2, 3);
Data data5 = new Data("2", "e", 3, 3);
Data data6 = new Data("3", "f", 1, 1);
// 多线程处理数据拼接
Thread t1 = new Thread(new MultiThreadJoiner(data1, cache));
Thread t2 = new Thread(new MultiThreadJoiner(data2, cache));
Thread t3 = new Thread(new MultiThreadJoiner(data3, cache));
Thread t4 = new Thread(new MultiThreadJoiner(data4, cache));
Thread t5 = new Thread(new MultiThreadJoiner(data5, cache));
Thread t6 = new Thread(new MultiThreadJoiner(data6, cache));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
```
阅读全文