简体   繁体   English

Java对象的并发

[英]Concurrency for objects in Java

I am currently working on an exercise in which I have to design a small and simple industrial factory in Java. 我目前正在做一个练习,我必须在Java中设计一个小型简单的工业工厂。 Basically I've got a warehouse for storage, machines that produce stuff and a GUI that takes commands and informs the user of the current stockpile of the different products, etc. 基本上,我有一个用于存储的仓库,生产东西的机器以及一个接受命令并通知用户不同产品当前库存的GUI,等等。

I've got almost everything working, however, with the limitation that only one machine can produce at a time right now. 但是,我几乎可以完成所有工作,但现在只能一次生产一台机器。 This is probably due to my approach to the whole exercise. 这可能是由于我对整个练习的态度。 I wanted to start small and just coded tiny units of the program that could work independently and then pieced them together one after another adding more and more logic to the application and implementing all the communication between the different classes, etc. 我想启动程序的小型单元,并对其进行编码,这些单元可以独立工作,然后将它们逐个拼凑在一起,为应用程序添加越来越多的逻辑,并实现不同类之间的所有通信,等等。

Now I am at the point where everything seems to be fine and the only thing left to do is to establish concurrency so that I can run several machines at the same time without any problems. 现在,我似乎一切都很好,剩下要做的就是建立并发性,这样我就可以同时运行多台机器而没有任何问题。

To give you a better understand, I'll try to outline my applications structure: 为了让您更好地理解,我将尝试概述我的应用程序结构:

First there's a GUI and a GUI Controller that assigns the tasks wanted by the user to the other Controllers in the application. 首先,有一个GUI和一个GUI控制器,可将用户所需的任务分配给应用程序中的其他控制器。 It also manages the updates for the GUI (stockpile, ...) 它还管理GUI的更新(库存,...)

Then I've got the warehouse section with the actual warehouse (HSQLDB, file based, JDBC connection) and a storageController, which controls all tasks regarding the warehouse (store products, remove products, get the stock, ...) 然后,我得到了带有实际仓库(HSQLDB,基于文件,JDBC连接)和storageController的仓库部分,该仓库控制器控制与仓库有关的所有任务(存储产品,删除产品,获取库存等)。

And finally there is the machine section. 最后是机器部分。 There are 3 types of machines. 有3种类型的机器。 Each type differs only in the product produced. 每种类型仅在生产的产品上有所不同。 Type 1 and 3 produce the raw products needed for type 2 to produce a final product. 1型和3型生产2型生产最终产品所需的原始产品。

In order to create as many machines as one likes to, I decided to use a Abstract Factory pattern to implement them. 为了创建尽可能多的机器,我决定使用Abstract Factory模式来实现它们。 That means that I've got an abstractMachineFactory, which holds all the needed attributes (like a machine ID, its status (on/off), ...) and methods including an abstract method "produce(boolean status)". 这意味着我有一个abstractMachineFactory,其中包含所有需要的属性(例如机器ID,其状态(打开/关闭)等)和包括抽象方法“ produce(boolean status)”的方法。 Status = true means that the machine is producing, false means that it's not. Status = true表示机器正在生产,false表示机器没有生产。

I gave each of the machine types its own class, so that I've got concreteMachineType1, concreteMachineType2 and concreteMachineType3. 我给每种机器类型都有自己的类,这样我就获得了ConcreteMachineType1,concreteMachineType2和concreteMachineType3。 In there the "produce()" method is implemented specifically to the machine type, ie type2's method checks (via the machineController) if there is a big enough stockpile of the raw products that type1 and 3 produce so that it can begin producing. 在这里,“ produce()”方法专门针对机器类型实施,即类型2的方法(通过machineController)检查类型1和3所生产的原始产品的库存是否足够大,以便可以开始生产。 As the machines should be continually producing, the body executes "while (status=true)". 由于机器应不断生产,因此主体执行“ while(status = true)”。 If the stockpile is not big enough, the machine will check again after a certain timeout (via the controller). 如果库存不足,则机器将在一定的超时后(通过控制器)再次检查。

And now we come to the machineController. 现在我们来看看machineController。 This controller manages all tasks regarding the individual machines. 该控制器管理有关各个机器的所有任务。 That means creating them, starting/stopping a single or all machines, get supplies from the warehouse, bring the final product from the interim storage to the warehouse, etc. 这意味着创建它们,启动/停止一台或所有机器,从仓库中获取物料,将最终产品从临时存储区带到仓库等。

In order to identify and access my machines, I've implemented different array lists (one for each machine type) in which the machine objects are stored, with the index of the array being the machines' ID. 为了识别和访问我的机器,我实现了存储机器对象的不同阵列列表(每种机器类型一个),阵列的索引是机器的ID。 This way I can start/stop a specific machine by accessing the index or start/stop all by parsing through the whole array list. 这样,我可以通过访问索引来启动/停止特定机器​​,或者通过解析整个数组列表来启动/停止所有机器。

When starting the machines I also execute the "produce()" method and this is where the problem is at the moment (in my opinion). 在启动机器时,我还执行“ produce()”方法,这就是当前问题所在(我认为)。

This is what happens: I create a few new machines (default is that they are turned off) and then execute my startAllMachines() method. 这就是发生的情况:我创建了一些新机器(默认情况下它们已关闭),然后执行我的startAllMachines()方法。 What this method will do is parsing through the array list and executing startMachine() on every single machine object in that list. 此方法将执行的操作是解析数组列表,然后对该列表中的每个机器对象执行startMachine()。 As said above, startMachine() also calls the produce() method of the machine. 如上所述,startMachine()也调用机器的produce()方法。

And now I'm basically in an infinite loop, as the produce() method of that machine will run as long as I turn it off, by setting its status value to false. 现在,我基本上处于一个无限循环中,因为只要将其状态值设置为false,该机器的produce()方法就会一直运行,直到我将其关闭。 That means that all other machines will not be turned on, so that only this single machine will produce and the rest is in a queue that will never be reached. 这意味着将不会打开所有其他计算机,从而仅会产生该单台计算机,而其余机器将永远无法到达。

I figure that I need different threads to work all machines concurrently, so that each machine is started by a different thread. 我认为我需要不同的线程来同时运行所有计算机,以便每台计算机由不同的线程启动。 The problem is that I have no clue on how to achieve this and the basic tutorials I've found didn't help me either. 问题是我对如何实现这一目标一无所知,而我发现的基本教程也无济于事。 Most of them suggested implementing Runable() and defining a run() method, but this isn't applicable in my scenario (imho). 他们中的大多数建议实现Runable()并定义一个run()方法,但这不适用于我的情况(恕我直言)。 What I think I need is concurrent machine starter objects or something. 我想我需要的是并发的机器启动器对象或其他东西。

I hope some of you can give me hints in how to proceed here. 我希望你们中的一些人可以给我一些提示,以提示您如何继续进行。

best regards daZza 最好的问候daZza

class Machine {

private Thread producerThread;

/**
 * Non blocking method that produces fixed amount of stuff and returns.
 */
private void produceStuff() {
    // TODO
}

private void startProducing() {
    Runnable producingTask = new Runnable() {
        public void run() {

            produce();
        }
    };

    producerThread = new Thread(producingTask);

    producerThread.start();
}

private void stopProducing() {
    if (producerThread != null) {
        producerThread.interrupt();
    }

}

/**
 * Check cancellation every time stuff is produced.
 */
private void produce() {
    while (!Thread.currentThread().isInterrupted()) {
        produceStuff();
    }
}

public void start() {
    startProducing();
}

public void stop() {
    stopProducing();
}

} }

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

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