首页 > 解决方案 > 通过工厂同步线程获取/创建

问题描述

我想要多个线程,每个线程都链接到一个“组”,它将执行操作。这些线程中的每一个,都会在一个循环中查看一个操作队列来做,并且它不是空的,它们将采取下一个操作并处理它。

就这么简单:

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 的正确线程(包含在操作中),创建它,给我现有的线程,或者在它检测到时停止并删除它对它没有新的操作

标签: javamultithreadingconcurrencysynchronizationconcurrenthashmap

解决方案


推荐阅读