首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java中使用线程将串行程序转换为并行程序?

在java中使用线程将串行程序转换为并行程序?
EN

Stack Overflow用户
提问于 2013-04-15 08:18:25
回答 2查看 1K关注 0票数 1

我正在为圣经编写一个文本搜索程序,我想使用线程来划分工作,以便减少执行时间。我对Java编程比较熟悉,但对整个“线程”的事情还是完全陌生的。基本上,这个程序是把圣经中不同的书拉出来,阅读文本,搜索单词,然后再拉下一本书。我想把它分开,这样4-8个线程可以同时在不同的书上工作。

有什么帮助吗?

代码语言:javascript
复制
public static void main(String args[]){

    String wordToSearch = "";
    String[] booksOfBible;
    int bookPosition = 0;
    ArrayList<String> finalList = new ArrayList<String>();

    getWord gW = new getWord();
    getBook gB = new getBook();
    checkBook cB = new checkBook();
    wordToSearch = gW.getWord(wordToSearch);
    booksOfBible = gB.getFileList();
    //System.out.println(wordToSearch);
    for(int i = 0; i < booksOfBible.length; i++){
        //System.out.println(booksOfBible[i]);//Test to see if books are in order
        String[] verses = gB.getNextBook(booksOfBible, bookPosition);
        //System.out.println(verses[0]);//Test to see if the books are being read properly
        cB.checkForWord(wordToSearch, verses, booksOfBible[i], finalList);
        bookPosition++;
    }
    for(int i = 0; i < finalList.size(); i++){
        System.out.println(finalList.get(i));
    }
    System.out.println("Word found " + finalList.size() + " times");
}
EN

回答 2

Stack Overflow用户

发布于 2013-04-15 08:25:38

您可以创建一个实现Runnable的类,并在run()方法中实现文本搜索。

然后,通过使用runnable对象作为构造函数参数创建一个新的thread对象,可以在新线程中运行它

代码语言:javascript
复制
Thread t = new Thread(myRunnableObj);
t.start();

假设您还需要一个数据结构,以供多个工作线程存储结果。确保使用线程安全/同步的数据结构

然而,正如Andrew Thompson所指出的,它可能会让你更快地索引整个圣经(例如:using MySql fulltext searching或其他库)

票数 0
EN

Stack Overflow用户

发布于 2013-04-15 08:29:58

使用Executors.newFixedThreadPool(nbNeededThreads)将为您提供一个ExecutorService实例,这将允许您提交并行任务。一旦得到了“未来”的列表,你就可以监控它们,知道它们什么时候都完成了。

代码语言:javascript
复制
ExecutorService service = Executors.newFixedThreadPool(4);
ArrayList<Future> queue = new ArrayList<>();

for(int i = 0; i < booksOfBible.length; i++){
    Futur futurTask = service.submit(searchingTask);
    queue.add(futurTask);
}

// TODO Monitor queue to wait until all finished.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16005866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档