- public class ShareArrThread {
- /*
- * 声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),
- * 给数组中添加数据,每一个线程为数组添加3个数据即可。
- *
- * 刚开始看视频,自己跟这写,感觉很乱很麻烦,现在整理下代码,供参考;
- * 主要地方做了封装和注释说明,应该能看的比较清楚;
- * 为主要代码看起来方便,异常在run中简单处理;
- */
- public static void main(String[] args)
- {
- //new两个线程,每个线程循环3次(不是这题要点);
- final Arr arr = Arr.getArr();
- new Thread(
- new Runnable()
- {
- public void run()
- {
- for(int i = 0;i<3;i++)
- try {arr.addA();} catch (InterruptedException e) {}
- }
- }
- ).start();
-
- new Thread(
- new Runnable()
- {
- public void run()
- {
- for(int i = 0;i<3;i++)
- try {arr.addB();} catch (InterruptedException e) {}
- }
- }
- ).start();
- }
- }
- class Arr
- {
- //以下三句为单例设计
- private Arr(){}
- private static Arr a = null;
- public static Arr getArr()
- {
- if(a==null)
- synchronized(Arr.class)
- {
- if(a==null)
- a = new Arr();
- }
- return a;
- }
- //下面两句数组相关初始化
- public int[] arr = new int[6];
- private int i = -1 ;
-
- //以下两个方法控制两个线程间隔调用
- boolean flag = true;
- public synchronized void addA() throws InterruptedException
- {
- while(flag)
- wait();
- add();
- }
- public synchronized void addB() throws InterruptedException
- {
- while(!flag)
- wait();
- add();
- }
- //添加元素核心方法
- public void add() throws InterruptedException
- {
- Thread.sleep((int)(Math.random()*1000));//每次添加间隔随机时间
- arr[++i]=(int)(Math.random()*100);//添加随机数到数组
- System.out.println(Thread.currentThread().getName()+"添加了元素"+arr[i]);
- flag = !flag;//倒置标记
- notify();
- }
- }
复制代码
|