- import java.lang.reflect.Array;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.Random;
- import java.util.concurrent.CopyOnWriteArrayList;
- import java.util.concurrent.Executor;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ScheduledThreadPoolExecutor;
- import java.util.concurrent.TimeUnit;
- //声明一个共享数组,起两个线程,
- //两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,
- //每一个线程为数组添加3个数据即可。
- public class Test21 {
- //写一个类实现Runnable接口,创建两个Thread对象传入该类
- //多线程操作共享数组需要同步synchronize
- public static void main(String...args){
- fillArray fa = new fillArray();
- Thread t1 = new Thread(fa);
- Thread t2 = new Thread(fa);
- t1.start();
- t2.start();
- }
- }
- class fillArray implements Runnable{
- //定义共享数组
- int[] arr = new int[6];
- Random r = new Random();
- int count = 0;
- public void run() {
- // 同步代码块
- synchronized(r){
- while(count<arr.length){
- int num = r.nextInt(20);
- System.out.println(Thread.currentThread().getName()+"向数组中加入了"+num);
- arr[count] = num;
- count++;
- try {
- r.wait(500);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- System.out.println(Arrays.toString(arr));
- }
-
- }
复制代码 |