如何解决使用 foreach 循环访问线程列表中的线程
我试图在 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>
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。