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

在java中使用线程将串行程序转换为并行程序?,java,multithreading,parallel-processing,full-text-search,Java,Multithreading,Parallel Processing,Full Text Search,我正在为《圣经》编写一个文本搜索程序,我想使用线程来划分工作,以便缩短执行时间。我对Java编程相当熟悉,但对整个“线程”完全陌生。基本上,这个程序是拉入圣经的单独书籍,阅读文本,搜索单词,然后拉入下一本书。我想把它分成4-8个线程,在不同的书上同时工作 有什么帮助吗 public static void main(String args[]){ String wordToSearch = ""; String[] booksOfBible; int bookPosit

我正在为《圣经》编写一个文本搜索程序,我想使用线程来划分工作,以便缩短执行时间。我对Java编程相当熟悉,但对整个“线程”完全陌生。基本上,这个程序是拉入圣经的单独书籍,阅读文本,搜索单词,然后拉入下一本书。我想把它分成4-8个线程,在不同的书上同时工作

有什么帮助吗

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");
}
publicstaticvoidmain(字符串参数[]){
字符串wordToSearch=“”;
字符串[]是一个二进制文件;
int bookPosition=0;
ArrayList finalList=新的ArrayList();
getWord gW=新getWord();
getBook gB=新的getBook();
支票簿cB=新支票簿();
wordToSearch=gW.getWord(wordToSearch);
booksofible=gB.getFileList();
//System.out.println(wordToSearch);
for(int i=0;i
您可以创建一个实现
Runnable
的类,并在
run()方法中实现文本搜索

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

Thread t = new Thread(myRunnableObj);
t.start();
您可能还需要一个多工作线程的数据结构来存储结果。确保使用线程安全/同步数据结构


然而,正如Andrew Thompson所指出的,使用Executors为整个圣经(例如:或其他库)编制索引可能会更快。

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

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.
ExecutorService=Executors.newFixedThreadPool(4);
ArrayList队列=新建ArrayList();
for(int i=0;i
通过制作文本的“词典”,可以实现更快的搜索。在这个问题上抛出额外的线程不太可能有帮助。“有帮助吗?”有(具体)问题吗?在深入研究多线程之前阅读一些教程是个好主意,例如,请参阅。并行编程是非常困难的,单线程编程的经验并不能让你真正做好准备。有些问题可以通过更好的数据结构而不是额外的资源得到更好的解决。我认为这是其中之一;建立索引以避免进行暴力搜索。如果在建立了一个高性能索引之后,您仍然需要它更快地运行,那么并行运行可能会有所帮助。(我怀疑这会有多大帮助;人们已经展示了对比《圣经》大得多的事物的极快搜索)。[旁注:使用严格编码的机器代码对圣经大小的文本缓冲区进行暴力搜索可能会以每秒千兆字节的速度进行搜索;这还不够快?]