Search code examples
javaloopsforeachjava-threads

Using a foreach loop to access threads in a list of threads


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();
    }

}

Solution

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