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 17:32:08 浏览: 90
很抱歉,我之前的回答有误,以下是新的回答:
可以使用线程同步和条件变量的方式来实现多线程读取数组,避免重复读取。以下是示例代码:
```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(0));
Thread t2 = new Thread(new MyRunnable(1));
Thread t3 = new Thread(new MyRunnable(2));
// 启动线程
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable {
private static int index = 0;
private static Object lock = new Object();
private int id;
public MyRunnable(int id) {
this.id = id;
}
@Override
public void run() {
while (index < ReadArray.arr.length) {
synchronized (lock) {
while (index % 3 != id && index < ReadArray.arr.length) {
// 当前线程不是该读取的线程,等待
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (index < ReadArray.arr.length) {
int num = ReadArray.arr[index];
index++;
System.out.println("线程" + (id+1) + ":读取" + num);
lock.notifyAll();
}
}
}
}
}
```
运行结果可能会因为线程执行顺序不同而不同,但是每个数值只会被读取一次,并且每个线程读取的数值不会重复。
阅读全文