package com.play;
import java.util.Random;
public class AddArray {
public static void main(String[] args) {
Add add = new Add();
new Thread(add, "线程1 :").start();
new Thread(add, "线程2 :").start();
}
}
class Add implements Runnable{
int[] arr = new int[6];
int i = 0;
private void addArray(int [] arr){
while(true){
synchronized(new Object()){
if(i < 6){
try{
wait(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
arr[i] = new Random().nextInt(6);
System.out.println(Thread.currentThread().getName() + "arr[" + i + "] = " + arr[i]);
i++;
notify();
}
}
}
}
public synchronized void run(){
addArray(arr);
}
} |