我正在为圣经编写一个文本搜索程序,我想使用线程来划分工作,以便减少执行时间。我对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");
}发布于 2013-04-15 08:25:38
您可以创建一个实现Runnable的类,并在run()方法中实现文本搜索。
然后,通过使用runnable对象作为构造函数参数创建一个新的thread对象,可以在新线程中运行它
Thread t = new Thread(myRunnableObj);
t.start();假设您还需要一个数据结构,以供多个工作线程存储结果。确保使用线程安全/同步的数据结构
然而,正如Andrew Thompson所指出的,它可能会让你更快地索引整个圣经(例如:using MySql fulltext searching或其他库)
发布于 2013-04-15 08:29:58
使用Executors.newFixedThreadPool(nbNeededThreads)将为您提供一个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.https://stackoverflow.com/questions/16005866
复制相似问题