简体   繁体   English

Java,系统架构,正确的实现

[英]Java, system architecture, correct implementation

I am not a java expert, and my question is somewhat abstract, i need an advice on how is a best to implement my suggested architecture and requirements. 我不是Java专家,我的问题有点抽象,我需要有关如何最好地实现建议的体系结构和要求的建议。

I will describe my requirements: 我将描述我的要求:

I have a manager object that receives tasks to process (holds aa task queue), the manager should distribute tasks between dedicated threads. 我有一个管理器对象,该对象接收要处理的任务(保存一个任务队列),该管理器应在专用线程之间分配任务。 each thread knows to execute only specific type of tasks. 每个线程都知道仅执行特定类型的任务。

I created a Main Manager class with a collection of type specific threads, When a Main manager receives a new task it will push a task to the queue of a thread class object that knows how to handle this task (each thread has it's own task queue). 我创建了一个具有特定类型线程集合的Main Manager类,当Main Manager收到新任务时,它将把一个任务推到知道如何处理该任务的线程类对象的队列中(每个线程都有自己的任务队列) )。

A thread need to pool a task from his queue when he finished to handle previous task, but if the queue is empty , he should not use resources and need to be awaken when a new task arrives. 当线程完成处理上一个任务时,线程需要从其队列中缓冲一个任务,但是如果队列为空,则他不应使用资源,并且在新任务到达时应将其唤醒。

My though (may be not so good) was to use threads that extend timer object and with a timed task of checking its queue, but this does not fit to my requirement to free resources until a new task arrives. 我的做法(可能不太好)是使用扩展计时器对象的线程,并使用定时任务检查其队列,但这不符合我释放资源直到新任务到来的要求。

Any suggestion of the best way to handle those system requirement will be appreciated (My Question is not a homework but rather a part of my developing tasks). 对解决这些系统要求的最佳方法的任何建议将不胜感激(我的问题不是家庭作业,而是我正在开发的任务的一部分)。

EDIT 编辑

(An answer to @Alexander Torstling) I am using currently a Blocking Queue as a tasks queue, my question is not a concurrency issue but rather an architectural , i want to free resources when the queue is empty and i want to be awaken maybe by event if a new task arrives, if i have finished handling with a task and i have more of them i will continue to handle next task; (@Alexander Torstling的答案)我目前正在使用阻塞队列作为任务队列,我的问题不是并发问题,而是架构问题,我想在队列为空时释放资源,并且想唤醒如果有新任务到来,如果我已经完成一个任务的处理并且我有更多的任务,那么我将继续处理下一个任务;

Have a look at BlockingQueue . 看看BlockingQueue And in order to avoid creating too many threads, you might want to consider using an Executor , which can manage a thread pool for you. 为了避免创建太多线程,您可能需要考虑使用Executor ,它可以为您管理线程池。

I would use an ExecutorService. 我将使用ExecutorService。 This wraps a Queue and a pool of Thread(s) 这包装了一个队列和一个或多个线程池

ExecutorService service = Executors.newXxxx(); // new thread pool.


service.submit(new Runnable() {
    public void run() {
        process(task);
    }
});

This way a single thread pool can process any number of different types of tasks (or just one if you prefer) 这样,单个线程池可以处理任何数量的不同类型的任务(如果愿意,也可以只处理一个)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM