编写一个程序,开启 3 个线程,去读取数组中的资源,要求读取 的数据不能重复 数组: public static int[] arr ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22, 23,24,25,26,27,28,29,30}; main 方法格式: public class ReadArray{ public static void main(String[] args) { } } 输出示例: 线程 1:读取 1,5,9,10,11,13..... 线程 2:读取 2,3,6,8,12..... 2 3 线程 3:读取 4,7,14,15,16.....
时间: 2023-05-20 08:00:46 浏览: 105
创建、增长并读取线程
好的,以下是我给出的代码:
import java.util.ArrayList;
import java.util.List;
public class ReadArray {
public static int[] arr ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
public static int threadNum = 3;
public static List<Integer>[] threadList = new List[threadNum];
public static void main(String[] args) {
for (int i = 0; i < threadNum; i++) {
threadList[i] = new ArrayList<>();
}
for (int i = 0; i < arr.length; i++) {
threadList[i % threadNum].add(arr[i]);
}
for (int i = 0; i < threadNum; i++) {
final int index = i;
new Thread(() -> {
System.out.print("线程 " + (index + 1) + ":读取 ");
for (int j = 0; j < threadList[index].size(); j++) {
System.out.print(threadList[index].get(j) + ",");
}
System.out.println();
}).start();
}
}
}
输出示例:
线程 1:读取 1,4,7,10,13,16,19,22,25,28,
线程 2:读取 2,5,8,11,14,17,20,23,26,29,
线程 3:读取 3,6,9,12,15,18,21,24,27,30,
阅读全文