声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,每一个线程为数组添加3个数据即可。- package p1;
- import java.util.Random;
- /**
- * 声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,每一个线程为数组添加3个数据即可。
- * @author wfq
- *
- */
- public class Test {
- public static void main(String[] args) throws InterruptedException {
-
- Demo d = new Demo();
-
- ThreadA t1 = new ThreadA(d);
- ThreadB t2 = new ThreadB(d);
-
- t1.start();
- t2.start();
-
- t1.join();
- t2.join();
-
- d.printArr();
-
- }
- }
- class Demo{
- private int[] arr = new int[6];
- private int pos;
- private boolean flag;
- Random r = new Random();
- public synchronized void setNum_1() {
- while(flag){
- try{this.wait();}catch (InterruptedException e) {}
- }
- arr[pos++] = r.nextInt();
- System.out.println(Thread.currentThread().getName()+"......"+r.nextInt());
- flag=true;
- this.notify();
- }
- public synchronized void setNum_2() {
-
- while(!flag){
- try{this.wait();}catch (InterruptedException e) {}
- }
- System.out.println(Thread.currentThread().getName()+"......"+r.nextInt());
- arr[pos++] = r.nextInt();
- flag=false;
- this.notify();
- }
- public void printArr() {
- for (int i : arr) {
- System.out.print(i);
- }
- }
- }
- class ThreadA extends Thread{
- private Demo a;
- public ThreadA(Demo a) {
- super();
- this.a = a;
- }
- public void run() {
- for (int i = 0; i < 3; i++) {
- a.setNum_1();
- }
- }
- }
- class ThreadB extends Thread{
- private Demo a;
- public ThreadB(Demo a) {
- super();
- this.a = a;
- }
- public void run() {
- for (int i = 0; i < 3; i++) {
- a.setNum_2();
- }
- }
- }
复制代码 感觉难点在于验证向共享数组中添加元素,一般我们选择打印数组,例如在主线程中打印。但是由于是多线程的,主线程可能瞬间执行完,可此时添加线程还未执行,我们很容易误会向共享数组中添加数据失败。其实是打印的时机不对而已。
|