- package com.itheima;
- import java.util.Arrays;
- import java.util.Random;
- public class Test6 {
- public static void main(String[] args) {
- AddArray a = new AddArray();
- Thread t1 = new Thread(a);
- Thread t2 = new Thread(a);
- t1.start();
- t2.start();
- }
- }
- class AddArray implements Runnable {
- // 定义数组
- private int[] arr = new int[10];
- // 定义指针
- private int pos = 0;
- public void run() {
- // 每个线程添加五个数字
- for (int x = 0; x < 5; x++) {
- // 获得随机数
- int temp = new Random().nextInt();
- synchronized (arr) {
- arr[pos] = temp;
- pos++;
- System.out.println(Thread.currentThread().getName()
- + "...添加了..." + temp);
- System.out.println(Arrays.toString(arr));
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- }
- }
- }
- }
复制代码 供楼主参考 |