java - 通过工厂同步线程获取/创建
问题描述
我想要多个线程,每个线程都链接到一个“组”,它将执行操作。这些线程中的每一个,都会在一个循环中查看一个操作队列来做,并且它不是空的,它们将采取下一个操作并处理它。
就这么简单:
public class GroupThreadManager {
private static ConcurrentHashMap<Long, GroupThread> threads = new ConcurrentHashMap<>();
private synchronized static void newOperation(Operation op) throws IOException {
final Long idGroup = op.getIdGroup();
if (!threads.containsKey(idGroup )) {
threads.put(idGroup , new GroupThread());
}
threads.get(idGroup ).start(op);
}
private synchronized static void interrupThread(Long id) {
if(threads.remove(id) == null) {
log.info("THIS SHOULDNT HAVE HAPPENED!!!!!");
}
}
}
public class GroupThread implements Runnable {
private Thread worker;
private ConcurrentLinkedQueue<Operation> operations = new ConcurrentLinkedQueue<>();
private Long idGroup;
public void start(Operation op) throws IOException {
addOperation(op);
if (worker == null) {
idGroup = op.getIdGroup();
worker = new Thread(this);
worker.start();
}
}
public synchronized void addOperation(Operation op) {
operations .add(user);
}
private synchronized int size() {
return operations.size();
}
public void run() {
while (size() > 0) {
operations.poll()
.compute() // do something here
}
GroupThreadManager.interrupThread(idUser);
}
}
如果使用该run
方法实现该方法,while (true)
我将没有问题。当我希望该线程处理它拥有的所有操作时,问题就出现了,并且每当它停止操作时,我想让该线程结束。我一直在尝试进行适当的同步以从 GroupThreadManager 创建/获取线程,但我总是陷入死锁,或者由于缺少同步而以新操作结束的线程继续进行。
这个想法是,我可以从程序的另一部分调用GroupThreadManager.newOperation(new Operation())
,并且该管理器自动为我提供该 groupId 的正确线程(包含在操作中),创建它,给我现有的线程,或者在它检测到时停止并删除它对它没有新的操作
解决方案
推荐阅读
- c++ - 如何使用 SDL2 在俄罗斯方块副本中实现 IO.cpp
- testing - 断言特定的 html 元素是 Cypress 中的按钮或选项卡
- python - SMTPSenderRefused: (530, b'5.7.0 必须先发出 STARTTLS 命令
- javascript - 使用 useState 计数直到问题 6 才更新状态,即使回答正确也是如此
- javascript - 如何在 ReactJS 的 javascript 对象中获取用户名和密码?
- python - 我可以在python中的一条线等距离处绘制一个点吗?
- python - Django多对多序列化程序循环依赖工作?
- javascript - jQuery & PHP - 菜单的条件渲染并将 PHP func 中的 HTML 内容传递到 jQuery
- flutter - 颤振问题:如何更新购物车中的商品数量?
- azure-devops - AzDO 管道:在扩展模板中继承阶段条件