Thread independent from the result

Asked

Viewed 54 times

1

I have a query where returns a list of results;

Example:

192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5

I would like from that list to create a thread for each one independent. For each to do their respective processing.

Currently I use only that waits for one to finish for the other to process

new Thread(){
        public void run(){
            MeuController mc = new MeuController();
            List lista = mc.getMetodo();
            Iterator it = lista.iterator();
            while( it.hasNext() ){
               Model model = (Model) it.next();
               //agora vai processar
            }
         }
    }.start();

Has as?

  • And is this chunk of code inside a loop? At what point are you waiting to thread finalize?

  • No. Only inside it that has a while

1 answer

2


Do it:

new MeuController().getMetodo().forEach(model -> {
    new Thread(() -> {
        //agora vai processar
    }).start();
});

Or else, you create a method like this:

private void processar(Model model) {
    //agora vai processar
}

And then do it:

new MeuController().getMetodo().forEach(model -> {
    new Thread(() -> processar(model)).start();
});
  • On that first option: how could I read that line Model model = (Model) it.next(); in case it would be iterator

  • 1

    @adventistaam Forget the Iterator, since Java 5, there is little or no need to work with Iterators directly, and from Java 8 even less. The forEach already takes care of the details of the iteration. All this supposes that the getMetodo() return a List<Model>.

  • Um, got it...

  • @adventistaam However, if your doubt is just read the line Model model = (Model) it.next();, That’s because the method next pull the next item to be iterated from inside the Iterator running through the List. Ideally, both the List as to the Iterator should be generic, so that the List<Model> creates a Iterator<Model> which causes the type of return of the method next() be a Model, which is assigned the variable model. However, as the List and the Iterator are without the generic type, the compiler sees Object as a return of next(), and so then you need a cast.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.