1

我正在爲聖經寫文本搜索程序,我想用線程來分割工作,以便減少執行時間。我對Java編程非常熟悉,但對整個「線程」來說卻是全新的。基本上,該計劃是拉動聖經的單獨書籍,閱讀文本,尋找單詞,然後拉下一本書。我想分解它,以便4-8個線程在單獨的書上同時工作。使用java中的線程將串行程序轉換爲並行程序?

有沒有什麼幫助?

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"); 
} 
+1

通過製作文本的「字典」可以實現更快的搜索。拋出此問題的額外線索不太可能有所幫助。 –

+0

*「有任何幫助?」*任何(特定)問題? –

+0

在深入多線程之前閱讀一些教程是一個好主意,請參閱[this](http://www.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html)。並行編程非常困難,而單線程編程的經驗並沒有真正爲你做好準備。 –

回答

0

您可以創建一個實現Runnable一類並實現你的文字run()方法內搜索。

這是然後在新線程運行的用了Runnable對象作爲構造函數的參數

Thread t = new Thread(myRunnableObj); 
t.start(); 

想必你還需要多個工作線程來存儲結果的數據結構,創建一個新的Thread對象。請確保您使用的線程安全/同步數據結構

但是安德魯·湯普森指出,這可能會更快,爲您指數整本聖經(如:using MySql fulltext searching或其他庫)

0

使用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.