通过工厂同步获取/创建线程

时间:2019-07-16 06:37:01

标签: java multithreading concurrency synchronization concurrenthashmap

我想要多个线程,每个线程都链接到一个“组”,该线程将执行操作。这些线程中的每一个都将循环查看要执行的Operations队列,并且该线程不为空​​,它们将执行下一个Operation并对其进行处理。

就这么简单

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

0 个答案:

没有答案