class Play8 {
public static void main(String[] args){
Array a = new Array(true);
Array a1 = new Array(false);
new Thread(a,"1号线程").start();
new Thread(a1, "2号线程").start();
}
}
class Array implements Runnable {
static int inpros;
static int outpros;
static int[] arr = new int[10];
static Object o1 = new Object();
boolean flag;
public Array(boolean flag){
this.flag = flag;
}
public void run(){
if (flag) {
synchronized(o1){
while (inpros<=9) {
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
}
arr[inpros]= (int)(100*Math.random())+1;
System.out.println(Thread.currentThread().getName() +"正在往数组里投入"+ arr[inpros++]);
if (inpros==10) {
inpros =0;
break;
}
}
}
}else {
synchronized(o1){
while (true) {
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"正在往数组里拿出"+ arr[outpros++]);
if (outpros ==10) {
outpros =0;
break;
}
}
}
}
}
}
|
|