Home > Back-end >  How to create multiple threads in java for items in a list?
How to create multiple threads in java for items in a list?

Time:05-31

I have a list of orders:

Order

  • Number
  • details

List orders

I need to create an array of multiple threads (limit 8 threads so that cpu doesn't overload), and to each thread assign an item in the list.

Currently I'm doing the following:

int limit = 8;
int size = orders.size();
j=0;

if(size <= 8) {
   limit = size;
} 

for(; j < size; j  = 8) {
   Thread[] threads = new Thread[limit];

    for (; index < threads.length; index  ) {
       threads[index] = new Thread(() -> {
           treatOrder(orders.get(j).getNUMBER());
       });
            
       j  ;
       threads[index].start(); 
    }

    for (Thread thread : threads) {
            thread.join();
    }
}

The problem is that if I do this, j is incremented but it doesn't pass to the thread and each thread will treat the same order.

How can I pass an order number (different) for each thread to treat?

CodePudding user response:

This is because you're using a non-final or non-effectively-final variable within a lambda. Lambda expressions are lexically scoped, which means that they do not introduce a new level of scope and that in order for them to use variables declared externally, they must be final or effectively final as Java creates a copy of these variables once the lambda expression is executed.

You could fix your code by declaring a temp var in your loop which holds the order number:

int limit = 8;
        int size = orders.size();
        int j = 0;

        if (size <= 8) {
            limit = size;
        }

        for (; j < size; j  = 8) {
            Thread[] threads = new Thread[limit];

            for (; index < threads.length; index  ) {
                String orderNumber = orders.get(j).getNUMBER(); 
                threads[index] = new Thread(() -> {
                    treatOrder(orderNumber);
                });

                j  ;
                threads[index].start();
            }

            for (Thread thread : threads) {
                thread.join();
            }
        }

Note: the temp var must be declared within the loop and not externally as this will make it an effectively final variable. This is because the variable is recreated at each iteration with one constant value that doesn't change during its existence.

  • Related