简体   繁体   中英

Defining Multiple Threads in Java

I am writing a program that reads words from a file and sorts them in alphabetical order. You provide the input and output files in the command line, and the program reads the words from the input file and writes a sorted list back to the output file. This is done, and it works as it should do. No questions here.

I am not looking for specific code, but rather help on how to approach a problem. The next part of the assignment states that in the command line, you are to be able to set the number of Threads you want the program to use in the sorting process.

For instance, if you compile with the following:

java Sort 12 infile.txt outfile.txt

The above program is meant to use 12 Threads to sort the words from "infile.txt". Each Thread is to sort a number of N = (numberOfWords)/(numberOfThreads) words. All the words are read into memory, before the Threads are started. I'm aware that this might sound cryptic, but I have been googling around looking for a good explanation on "multithreading"/defining the number of Threads in a Java program, yet I am not any wiser.

If anyone knows how to explain how you can set the number of Threads in Java, even with a small example, I would be very grateful!

Thanks!

Oh sure. Well a thread is just a class with a "run" method.

You create the class and either have it extend Thread or implement Runnable. If you extend thread you can just call Thread.start() on it and that would start the thread. If you implement Runnable instead you have to so something like Thread t = new Thread(yourRunnableClass);, and then start T.

So for your example:

    public class Sort {

        class RunnableClass implements Runnable(){
            String args;
            RunnableClass(String[] args){
               this.args = args;
            }
            run(){
               //Do your sorting
            }
        }

        public static void main(String[] args){
            //some code that chops the args beyond arg 0 into arrays or something
            int numberOfThreads = Integer.parseInt(args[0]);
            for(int x=0;x<numberOfThreads;x++){
               Thread t = new Thread(new RunnableClass(String[] wordsToSort));
            }
            //something to manage the threads and coordinate their work
        }
    }

You could make this more elaborate or complex, one simple implementation would be to just loop over the words, passing 2 to each thread to sort and then once the threads complete if the order didn't change increment along the list till no orders change. That's a form of bubble sort. So in other words Thread A sorts words 1 and 2 Thread B sorts words 3 and 4 and so on.

The threads can communicate with each other, share state or have their own state, etc. There are many ways to implement this.

The threads could terminate, or be re-entrant, could have state, etc.

You could use the Executors.newFixedThreadPool(int nThreads) method (see details here ) to get a ThreadPool with the required number of threads. Then, divide your work into the appropriate number of chunks (12 in your example), create a Runnable object for each chunk of work and pass those Runnable objects to the ThreadPool's submit method.

Executors class has static newFixedThreadPool (int numberOfThreads) that can be given the number of threads to pool. For example, if you have class implementing Runnable

    public class MyCustomThread implements Runnable { 

    @Override
    public void run() {
    //do your work
    }
}

you can create pool with 5 threads like this

   ..
    int numberOfThreads = 5;
    ExecutorService srv = Executors.newFixedThreadPool(numberOfThreads);

    for (int i = 0; i < numberOfThreads; i++) {
            srv.execute(new MyCustomThread());
    }

Using ExecutorService it will be much easier for you to manage lifecycles of threads. Read Oracle concurrency tutorial for more information.

Here I want to ask you one question is which version of java you are using. As this task is not trivial to achieve as you are required to take care of couple things like threads join etc. Java 7 has a feature ' Fork/Join ' by which you can leverage the task.

You can refer the following for an example.

Sorting using Fork/Join

You can start from this

What you're looking for is a Fork/Join framework. This splits a single task into parts, handing the parts to multiple threads to be processed.

ExecutorService's FixedThreadPool allows you to create 12 worker threads, but leaves you with all the hard work of separating the work between the threads. The Fork/Join framework makes this easy, using a recursive system to break the process down if needed so it could be split between threads.

http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html

define a runnable, then in a loop add new threads with that runnable to a list. then start all the threads, either in the same loop or a separate one, passing all the words you need to process to each runnable on construction? you will also have to control access to the output file, and possibly the input file depending on how you access it, otherwise your thread will run into trouble, so take a look at race-conditions and how to deal with them

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