- import java.util.Random;
- public class ShareArrThread {
- /*
- * 声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),
- * 给数组中添加数据,每一个线程为数组添加3个数据即可。
- */
- public static void main(String[] args)
- {
- final Arr arr = Arr.getArr();
- new Thread(
- new Runnable()
- {
- public void run()
- {
- for(int i = 0;i<3;i++)
- arr.addA();
- }
- }
- ){}.start();
- new Thread(
- new Runnable()
- {
- public void run()
- {
- for(int i = 0;i<3;i++)
- arr.addB();
- }
- }
- ){}.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;
- }
- int[] arr = new int[6];
- int i = -1;
- boolean flag = true;
- public synchronized void addA()
- {
- while(flag)
- try {
- wait();
- Thread.sleep(new Random().nextInt(2000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"添加了"+(arr[++i]=new Random().nextInt(2000))+";");
- flag = !flag;
- notify();
- }
- public synchronized void addB ()
- {
- while(!flag)
- try {
- wait();
- Thread.sleep(new Random().nextInt(2000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"添加了"+(arr[++i]=new Random().nextInt(2000))+";");
- flag = !flag;
- notify();
- }
- }
复制代码 |