package ThreadTest1;
import java.util.Random;
/*
* 开启两个线程每隔一段时间分别向一个共享数组中添加元素,
* 每个线程添加3个即可
*/
public class Test2 {
public static void main(String[] args) {
Arr arr = new Arr();
FirstThread ft = new FirstThread(arr);
ScendThread st = new ScendThread(arr);
Thread t1 = new Thread(ft, "线程A");
Thread t2 = new Thread(st, "线程B");
t1.start();
t2.start();
}
}
class Arr {
int[] array = new int[6];
boolean flag;
}
class FirstThread implements Runnable {
private Arr arr;
public FirstThread(Arr arr) {
this.arr = arr;
}
int num = 0;
public void run() {
while (num < 5) {
synchronized (arr) {
if (arr.flag) {
try {
arr.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
int number = new Random().nextInt(10);
arr.array[num] = number;
System.out.println(Thread.currentThread().getName() + "给第"
+ (num + 1) + "项添加数字" + number);
arr.flag = true;
num += 2;
arr.notify();
}
}
}
}
class ScendThread implements Runnable {
private Arr arr;
public ScendThread(Arr arr) {
this.arr = arr;
}
int num = 1;
public void run() {
while (num < 6) {
synchronized (arr) {
if (!arr.flag) {
try {
arr.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
int number = new Random().nextInt(10);
arr.array[num] = number;
System.out.println(Thread.currentThread().getName() + "给第"
+ (num + 1) + "项添加数字" + number);
arr.flag = false;
num += 2;
arr.notify();
}
}
}
}
这样做有什么不妥或者可以优化写法的吗? |
|