交替打印两个数组的元素
int[] arr1 = new int[]{1, 3, 5, 7, 9};
int[] arr2 = new int[]{2, 4, 6, 8, 10};
分析:两个数组分别打印,那么一定需要一个标识来代表打印哪一个数组中的元素。
public class 交替打印两个数组 {
int[] arr1 = new int[]{1, 3, 5, 7, 9};
int[] arr2 = new int[]{2, 4, 6, 8, 10};
private boolean flag =true;
public static void main(String[] args) {
交替打印两个数组 交替打印两个数组 = new 交替打印两个数组();
new Thread(() -> {
交替打印两个数组.print1();
}).start();
new Thread(() -> {
交替打印两个数组.print2();
}).start();
}
public synchronized void print1(){
for (int i : arr1) {
while (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
flag=!flag;
this.notify();
}
}
public synchronized void print2(){
for (int i : arr2) {
while (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
flag=!flag;
this.notify();
}
}
}
本文转自 jimolvxing.blog.csdn.net/article/det…,如有侵权,请联系删除。