2. 编写一个程序,开启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 线程2:读取3 线程3:读取4, 线程1:读取6 线程2:读取2 线程3:读取5,
时间: 2023-07-27 14:32:08 浏览: 68
java对大数据量文件内容的多线程读取和排序.zip_大数据 java_文件读取
可以使用线程同步的方式来实现多线程读取数组,避免重复读取。以下是示例代码:
```java
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 void main(String[] args) {
// 创建三个线程
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
// 启动线程
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable {
private static int index = 0;
private static Object lock = new Object();
@Override
public void run() {
while (true) {
synchronized (lock) {
if (index >= ReadArray.arr.length) {
break;
}
int num = ReadArray.arr[index];
index++;
System.out.println("线程" + Thread.currentThread().getName() + ":读取" + num);
}
}
}
}
```
运行结果可能会因为线程执行顺序不同而不同,但是每个数值只会被读取一次。
阅读全文