写一个Java线程池工具类,实现功能,具备相同uuid的消息事件由同一个线程按照消息事件接收顺序执行,要求高效,使用hash映射uuid,提供代码和测试方法
时间: 2023-07-18 14:32:52 浏览: 100
java常用工具类 UUID、Map工具类
以下是一个简单的Java线程池工具类,它基于UUID和HashMap实现了按顺序处理具有相同UUID的消息事件。它使用了一个自定义的Runnable实现,其中包含了消息处理事件和UUID信息。该工具类具有以下功能:
1. 创建线程池
2. 将消息事件提交到线程池中
3. 按照UUID将消息事件分配到不同的线程中,并按照消息事件接收顺序执行
```java
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class UUIDThreadPool {
private final ExecutorService executor;
private final Map<UUID, UUIDRunnable> uuidMap;
public UUIDThreadPool(int poolSize) {
this.executor = Executors.newFixedThreadPool(poolSize);
this.uuidMap = new HashMap<>();
}
public void submit(UUID uuid, Runnable runnable) {
synchronized (uuidMap) {
UUIDRunnable uuidRunnable = uuidMap.get(uuid);
if (uuidRunnable == null) {
uuidRunnable = new UUIDRunnable(uuid);
uuidMap.put(uuid, uuidRunnable);
executor.submit(uuidRunnable);
}
uuidRunnable.addRunnable(runnable);
}
}
private class UUIDRunnable implements Runnable {
private final UUID uuid;
private final Object lock;
private final Queue<Runnable> queue;
public UUIDRunnable(UUID uuid) {
this.uuid = uuid;
this.lock = new Object();
this.queue = new LinkedList<>();
}
public void addRunnable(Runnable runnable) {
synchronized (lock) {
queue.offer(runnable);
lock.notifyAll();
}
}
@Override
public void run() {
while (true) {
Runnable runnable;
synchronized (lock) {
while (queue.isEmpty()) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
runnable = queue.poll();
}
runnable.run();
}
}
}
}
```
测试方法如下:
```java
public static void main(String[] args) {
UUIDThreadPool threadPool = new UUIDThreadPool(2);
UUID uuid = UUID.randomUUID();
for (int i = 0; i < 5; i++) {
int j = i;
threadPool.submit(uuid, () -> System.out.println("Task " + j + " for UUID " + uuid));
}
}
```
该测试方法将创建一个随机UUID,然后将5个任务提交到线程池中,这些任务具有相同的UUID。由于线程池的大小为2,因此将使用2个线程来处理这些任务。每个线程将依次处理具有相同UUID的任务,以保证按顺序执行。
阅读全文