简体   繁体   English

Java并发,读取文件创建对象并存储它们

[英]Java concurrency, read files create objects and store them

I'm currently using java.nio to read files (using Files.readAllLines ) and then each line is passed to create an object [ new Object(line)] and the object is added to a collection. 我当前正在使用java.nio读取文件(使用Files.readAllLines ),然后传递每一行以创建一个对象[ new Object(line)]并将该对象添加到集合中。

Each file is parsed differently so that there is 3 types of objects, 2 of those are added to a map and they should be done first as they third adds to a set and gets added to a variable inside both of the previous maps [using something like that: 每个文件的解析方式都不相同,因此有3种类型的对象,其中2种被添加到映射中,应该先完成,然后再将它们添加到集合中,然后再添加到前两个映射中的变量中(使用某种方法)像那样:

get(var).x.add(Object)].

I don't really understand how to code concurrently and was having trouble finding anything close to this but I imagine it's possible to use concurrency to create the first two collections or to use it in all three and have do the final lot last (or get it to wait and do it later if the variables it needs to edit haven't been set yet). 我不太了解如何并行编码,并且很难找到与此类似的任何东西,但是我想可以使用并发创建前两个集合,或者在所有三个集合中使用它,然后最后做最后一批(或得到)如果尚未设置需要编辑的变量,请稍后再执行)。

Any help would be appreciated and if you need any clarification in what I'm looking for just ask. 任何帮助将不胜感激,如果您需要任何关于我正在寻找的说明,请问一下。

So you have 3 files and 2 of which are to put into a map, and the last file is for adding to some value of the map, right? 因此,您有3个文件,其中2个要放入地图,最后一个文件用于添加地图的某些值,对吗?

You could create threads for each of two files and put data into map. 您可以为两个文件中的每个文件创建线程,然后将数据放入地图。 Important thing here is that you must use concurrent data structure like ConcurrentHashMap or synchronized map. 重要的是,您必须使用并发数据结构,例如ConcurrentHashMap或同步映射。

I would use the following global steps to do this concurrently: 我将使用以下全局步骤来同时执行此操作:

  1. Create a threadpool of a certain size: Executors. newFixedThreadPool(someSize) 创建特定大小的线程池: Executors. newFixedThreadPool(someSize) Executors. newFixedThreadPool(someSize)
  2. Create three concurrent/synchronized sets. 创建三个并发/同步集。 One for each object type: Collections.synchronizedSet(new HashSet<YourObjectType>()); 每个对象类型一个: Collections.synchronizedSet(new HashSet<YourObjectType>());
  3. Use the threadpool to work through all the files adding to the synchronized sets when appropriate 在适当的情况下,使用线程池处理添加到同步集的所有文件
  4. When all files have been processed the first to lists/collections have the initial objects, then loop through the last set containing the values that need to be added to instances of the first 2 sets. 处理完所有文件后,第一个到列表/集合的文件将具有初始对象,然后循环浏览最后一个包含需要添加到前两个集合的实例中的值的集合。 If this list is very large you can split it up in pieces and also do this concurrently. 如果此列表很大,则可以将其拆分成多个部分,也可以同时进行。

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

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