简体   繁体   中英

Converting serial program to parallel using threads in java?

I am writing a text search program for the Bible and I want to use threads to divide up the work so that the execution time cuts down. I'm moderately familiar with programming in Java, but completely new to the whole "threads" thing. Basically, the program is pulling the separate books of the Bible, reading the text, searching for the word, and then pulling in the next book. I want to divide this up so that 4-8 threads are working concurrently on separate books.

Any assistance?

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

You can create a class that implements Runnable and implement your text searching inside the run() method.

This is then runnable in a new thread by creating a new Thread object with the Runnable object as the constructor argument

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

Presumably you'll also need a data structure for multiple worker thread to store the result. Make sure you use thread-safe / synchronized data structure

However as Andrew Thompson pointed out, it might be faster for you to index the whole bible (eg: using MySql fulltext searching or other libraries)

Using Executors.newFixedThreadPool(nbNeededThreads) would give you an ExecutorService instance and this would let you submit parrallel tasks. Once getting the list of "Future", you can monitor those and know when their all done.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM