-1

I am trying to iterate over threads in a foreach loop, but I get an error: Type mismatch: cannot convert from element type Object to Thread

The loop is in private static void waitForThreads(List threads)

import java.util.*;

public class ThreadCreator {

    public static void multiply(int[][] matrix1, int[][] matrix2, int[][] result) {

        List threads = new ArrayList<>();
        int numberOfRows = matrix1.length;

        for (int i = 0; i < numberOfRows; i++) {
            MatrixRow row = new MatrixRow(result, matrix1, matrix2, i);
            Thread thread = new Thread(row);
            thread.start();
            threads.add(thread);
            if (threads.size() % 10 == 0) {
                waitForThreads(threads);
            }
        }
    }

    private static void waitForThreads(List threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        threads.clear();
    }

}
  • 3
    In order for that to work the List must be declared as `List`. – markspace Mar 10 '21 at 23:26
  • 1
    You specify no type argument for `threads`, so it defaults to `Object`. What would happen if you added an integer to `threads`? Think about that. You probably want `List threads`. – Charlie Armstrong Mar 10 '21 at 23:27
  • Did you apply it in both locations? You declare it as a local variable in `multiply()` and as a parameter in `waitForThreads()`, so you need to specify the type argument in both locations. – Charlie Armstrong Mar 10 '21 at 23:39
  • @CharlieArmstrong FYI: There is a fine difference. See [this](https://stackoverflow.com/a/2770692/12323248), around the middle. – akuzminykh Mar 10 '21 at 23:50
  • @akuzminykh Good point, thanks. I think I've read that exact post before but I had forgotten the details. In the OP's specific situation, it amounts to the same behavior, but it's definitely an important difference. – Charlie Armstrong Mar 11 '21 at 00:05

1 Answers1

0

In your waitForThreads method you haven't specified the generic type of your List argument. You should be using:

List<Thread>

otherwise a List is just effectively a List<Object>.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44