简体   繁体   中英

How to create multiple threads in java for items in a list?

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?

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 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.

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