简体   繁体   中英

How to execute multiple instances of a method with different inputs in parallel in java?

I have a method which takes a list and do some processing on it and it updates another global list. I need to run multiple instances of this method with different lists input in parallel. Does multi-threading support this? If yes, how can i use it ie: what shall i put in the thread? Examples are highly appreciated.


I am thinking of having a static list in the thread class which gets updated by the different instances of the thread while running (the list contains strings and counters, so the update is adding new strings or increasing the counters of existing ones).. i need to read whatever gets added to this global list every 10 seconds and print it.. is using static list suitable for this and how can i make it thread safe?

Yes, that's a very common usage of multithreaded programming.

class ListProcessor implements Runnable {
    /* field/s representing param/s */
    public ListProcessor(/* param/s */) {
        /* ... */
    }

    @Override
    public void run() {
        /* process list */
    }
}

Then, when you want to actually process some lists.

class SomeClass {
    ExecutorService listProcessor;
    public SomeClass(/* ... */) {
        listProcessor = ExecutorService.newFixedThreadPool(numThreads);
        /* for each thread, however you want to do it */
        listProcessor.execute(new ListProcessor(/* param/s */));
        /* when finished adding threads */
        listProcessor.shutdown();
        /* note that the above two lines of code (execute/shutdown) can be
         * placed anywhere in the code. I just put them in the constructor to
         * facilitate this example.
         */
    }
}

@purtip31 has a start for the parallel processing stuff.

I'm concerned about the results - you mention that you update a "global list". If multiple threads at a time are trying to update that list at the same time there could be problems. A couple of options:

  1. Make sure that list is properly thread safe. This may or may not be easy - depends on exactly what is getting changed.
  2. Use ExecutorService , but with the invokeAll() method, which runs a bunch of Callables in parallel and waits till they are all done. Then you can go through all of the results and update them one at a time . No threading issues with the results. This means that your code will have to implement Callable instead of Runnable (not a big deal). I have a blog with an example here

Well Sam...im not much cleared with your question.....

try this out....

Following is a code which would help u to run mulitple instances.......

Main thread

    public class mainprocess
    {

          public static LinkedList globallist;
          public static String str;
          public int num;
          public static void main(String Data[])
          { 
                 globallist = new LinkedList();
                 // LinkedList will be passed as pass by reference.....
                 // globalist is made static and assigned likewise for global use..
                 childprocess.assignlist(globallist);
                 childprocess p1 = new childprocess("string input");  // a string input...
                 childprocess p2 = new childprocess(number input);   // a number input...


                 p1.t.join();
                 p2.t.join();
           }
     }

The Child Thread.....

     public class childprocess implements Runnable
     {
               public Thread t1,t2;
               public boolean inttype,stringtype;     
               String string;
               int num;
               public static LinkedList temp = new Linkedlist();
               public static assignlist(LinkedList ll)
               {
                       temp = ll;
               }
               public childprocess(String str)
               {
                        string = str;
                        t1 = new Thread(this,"stringThread");
                        t1.start();
               }

               @override
               public childprocess(int n)
               {
                         num = n;
                         t2 = new Thread(this,"numberThread");
                         t2.start();
               }

               @override 
               public void run()
               {
                         // Both will be executed in a threader manner based on the condition...
                         if(Thread.currentThread().getName().equals("stringThread")
                         {
                               // your process using string......
                               childprocess.temp.add(str);
                         }
                         else if(Thread.currentThread().getName().equals("numberThread")
                         {
                                 // your process using number.....
                                 chilprocess.temp.add(num);
                         }
                }                              

        }         

If you are using functions that should be restricted to only one thread at a time ...

include the syntax....

   public synchronized func_type func_name()
   {


   }

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