创建在后台执行特定任务的工作线程 [英] Create worker thread which performs specific task in the background

查看:60
本文介绍了创建在后台执行特定任务的工作线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的项目,

已通过查询从数据库中获取数据,结果集上有一个迭代器,并且数据已经不断地添加到这个结果集中.

Data has been fetched from database through a query, There is an Iterator on result set and data has been added continuously to this result set.

通过迭代 Iterator 对象,结果被添加到 ArrayList.一旦我们获得了所有条目(超过 200000 个),然后将其写入文件.

By iterating over Iterator object results are added to ArrayList. Once we got all the entries (more than 200000) then writing it to a file.

但是由于它使用了更多的 jvm 堆空间,我需要使用一个在后台运行并将数据写入文件的工作线程.

But as it is using more heap space of jvm ,I need to use a worker thread which runs in back ground and writes the data to the file.

由于我是多线程的新手,我想通过创建 1 个线程的固定线程池来使用 Executor 服务,每当条目达到 50000 计数时,然后将这些条目提交给执行程序以将它们附加到文件中.

As I am new to multi threading , I thought of using Executor service by creating fixed thread pool of 1 thread and whenever entries reaches the count of 50000 ,then submit those entries to executor to append them to file.

请建议我这种方法是否合适,或者我是否需要遵循任何其他方法.

please suggest me if this approach is fine or do I need to follow any other approach.

推荐答案

创建工作线程,在后台处理条目.在获取条目之前启动此线程,并在获取所有条目后停止,

Created worker thread which process entries in the beckground.Starting this thread before fetching entries and stopping it when finished fetching all entries,

public class WriteToOutputFile implements Runnable{
BlockingQueue<entry> queue;
File file;
volatile boolean processentries;
WriteToOutputFile(BlockingQueue queue,File file){
this.queue = queue;
this.file = file;
this.processentries= tue;
}

@override 
public void run(){
while(processentries && !queue.isEmpty()){
  entry = queue.take();

if (entry== lastentry)break;
//logic to write entries to file 
} }

public void stop(){
processentries = false;
queue.put(lastentry);
}
}

这篇关于创建在后台执行特定任务的工作线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆