本帖最后由 dangyongping 于 2016-5-12 07:24 编辑
- <div class="blockcode"><blockquote>package com.heima.lianxi1;
- import java.util.Random;
- public class Xiancheng {
- /**
-
- * 21、声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,
- * 每一个线程为数组添加3个数据即可。
- */
- public static void main(String[] args) {
- new X().start();
- new X().start();
- }
- }
- class X extends Thread{
- private static int[] arr = new int[6]; //不能省略
- public void run(){
- int a=0; //位置不能改变,在循环内自增后再次进入循环
- while(true){
- synchronized (X.class) {
-
- if (a>=3) { //循环判断条件,
- break;
- }
- try {
- Thread.sleep(300);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- Random r = new Random();
- arr[a] = r.nextInt(10);
-
- System.out.println(getName()+"集合中加了"+arr[a]);
- a++; //位置不能改变,
- }
- }
- }
- }
复制代码
|
|