使用 foreach 循环访问线程列表中的线程

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

我试图在 foreach 循环中迭代线程,但出现错误:Type mismatch: cannot convert from element type Object to Thread

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

}

在您的 waitForThreads 方法中,您没有指定 List 参数的通用类型。你应该使用:

List<Thread>

否则 List 实际上只是 List<Object>