package com.gu.test2;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @ClassName Test2
* @Description
* @Author Gu
* @Date 2019/11/22 11:10
* @Version V1.0
**/
public class TestCountDownLatch {
private static int threadCount = 0;
private static List<List<IpEntity>> zongData = new CopyOnWriteArrayList<>();
private static volatile List<IpEntity> ips = new CopyOnWriteArrayList<>();
public static String getIp() {
return "ip";
}
public static void main(String[] args) throws InterruptedException {
//判断缓冲ip集合是否大于10个ip,如果大于,开启新线程
new Thread(() -> {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//如果缓冲集合大于10个ip
if (ips.size() > 10) {
//创建新的集合
List<IpEntity> ips1 = new CopyOnWriteArrayList<>();
//添加10个ip
for (int i = 0; i < 10; i++) {
ips1.add(ips.get(i));
}
//统计线程数加一
threadCount++;
//总数据集合加入这个集合
zongData.add(ips1);
int threadNum = threadCount;
//创建新线程循环判断这个10个Ip
new Thread(() -> {
while (true) {
String ip = getIp();
for (IpEntity ipEntity : zongData.get(threadNum)) {
if (ip.equals(ipEntity.getIp())) {
Long newTime = System.currentTimeMillis();
if (ipEntity.getOutTime() < newTime) {
//设置过期
//删除ip
ips.remove(ipEntity);
} else {
ipEntity.setOutTime(System.currentTimeMillis() + 2000);
ips.set(ipEntity.getIndex(), ipEntity);
}
break;
}
}
//如果都为离线就退出线程
if(zongData.get(threadNum).size() == 0){
zongData.remove(threadNum);
return;
}
}
}, "工作线程" + threadCount).start();
//情况缓冲集合ip
for (int i = 0; i < 10; i++) {
ips.remove(i);
}
}
}
}, "ipsCountIs10").start();
//缓冲主线程
while (true) {
//获取Ip
String ip = getIp();
boolean flag = true;
for (IpEntity ipEntity : ips) {
if (ip.equals(ipEntity.getIp())) {
flag = false;
Long newTime = System.currentTimeMillis();
if (ipEntity.getOutTime() < newTime) {
//设置过期
//删除ip
ips.remove(ipEntity);
} else {
//更新时间戳
ipEntity.setOutTime(System.currentTimeMillis() + 2000);
ips.set(ipEntity.getIndex(), ipEntity);
}
break;
}
}
if (flag) {
//如果没有此Ip就添加
ips.add(new IpEntity(ip, System.currentTimeMillis() + 2000, ips.size()));
}
}
}
}
自用
最新推荐文章于 2023-01-20 20:31:55 发布