package com.heima.Test;
import java.util.Random;
public class Test5 {
/**
* 1.创建一个长度为6的数字;
* 2.创建线程1往数组添加一个元素
* 3.创建线程2往数组添加一个元素
* 4.加入等待唤醒机制
* 5.元素添加完毕,输出数组
*/
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
this.setName("线程一");
while(true) {
try {
p.print1();
if (Printer.i==5) {
System.out.println("数组输入完成");
StringBuilder sb = new StringBuilder("[");
for(int i = 0; i<p.arr.length; i++) {
if(i != p.arr.length-1) {
sb.append(p.arr[i]);
sb.append(", ");
} else {
sb.append(p.arr[i]);
sb.append(']');
}
}
System.out.println(sb);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
this.setName("线程二");
while(true) {
try {
p.print2();
if (Printer.i==5) {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Printer {
private int flag = 1;
static int[] arr = new int[6];
static int i=0;
public void print1() throws InterruptedException {
synchronized(this) {
if(flag != 1) {
this.wait();
}
Random r = new Random();
arr[i]=r.nextInt(20);
System.out.println(Thread.currentThread().getName()+"往数组里存入了"+arr[i]);
i++;
flag = 2;
this.notify();
}
}
public void print2() throws InterruptedException {
synchronized(this) {
if(flag != 2) {
this.wait();
}
Random r = new Random();
arr[i]=r.nextInt(20);
System.out.println(Thread.currentThread().getName()+"往数组里存入了"+arr[i]);
i++;
flag = 1;
this.notify();
}
}
}
线程二老是在后面跳来跳去的!
|
|