我正在编写一个圣经文本搜索程序,我想使用线程来划分工作,以减少执行时间。我对 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");
}
最佳答案
您可以创建一个实现 Runnable
的类,并在 run()
方法中实现文本搜索。
然后通过使用 Runnable 对象作为构造函数参数创建一个新的 Thread 对象,可以在新线程中运行
Thread t = new Thread(myRunnableObj);
t.start();
大概您还需要一个用于多个工作线程的数据结构来存储结果。确保使用线程安全/同步数据结构
但是,正如安德鲁·汤普森指出的那样,对整本圣经进行索引可能会更快(例如:using MySql fulltext searching或其他图书馆)
关于java - 使用java中的线程将串行程序转换为并行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005866/