黑马程序员技术交流社区

标题: 帮忙解答下注释的地方 [打印本页]

作者: 在学野马    时间: 2014-10-1 21:45
标题: 帮忙解答下注释的地方
本帖最后由 在学野马 于 2014-10-2 09:13 编辑
  1. public class xian implements Runnable{
  2. private static int[] arr = new int[6];
  3. private static int index = 0 ;
  4. public static void main(String[] args) throws Exception{
  5.   new Thread(new xian()).start();
  6.   new Thread(new xian()).start();  
  7.   Thread.sleep(2000);
  8.   for(int i : arr){
  9.    System.out.print(i+"\t"+"aaaaa");
  10.   }
  11. }

  12. public void run() {
  13.   try {  
  14.    Thread.sleep(1000);
  15.   } catch (InterruptedException e) {
  16.    e.printStackTrace();
  17.   }
  18.   for(int i=0;i<3;i++){                                     //我已经定义了输出三个数 为什么不管用
  19.    int number = (int)(Math.random()*10+1);
  20.    synchronized (xian.class) {
  21.     arr[index] = number;
  22.     System.out.println(arr[index]+"bbbbbbbb");
  23.     index++;
  24.    }
  25.   }  
  26. }
  27. }
复制代码



作者: wtjohn    时间: 2014-10-1 22:49
两个线程分别输出了3个数啊{:3_46:}
作者: 在学野马    时间: 2014-10-1 22:55
wtjohn 发表于 2014-10-1 22:49
两个线程分别输出了3个数啊

你发个截图
作者: wtjohn    时间: 2014-10-1 23:15
{:3_58:} 基础我也没看完呢...有点迷糊...不过你这个.应该是两个线程,不管有没有获得锁,都已经是在for循环里了..所以就生成了6个随机数,对吧? 是不是这个情况
作者: wtjohn    时间: 2014-10-1 23:20
  1. public class xian implements Runnable{
  2. private static int[] arr = new int[6];
  3. private static int index = 0 ;
  4. public static void main(String[] args) throws Exception{
  5.   new Thread(new xian()).start();
  6.   new Thread(new xian()).start();  
  7.   Thread.sleep(2000);
  8.   for(int i : arr){
  9.    System.out.print(i+">>>a     ");
  10.   }
  11. }

  12. public void run() {
  13.   try {  
  14.    Thread.sleep(1000);
  15.   } catch (InterruptedException e) {
  16.    e.printStackTrace();
  17.   }
  18.   for(int i=0;i<3;i++){                                     //我已经定义了输出三个数 为什么不管用
  19.           synchronized (xian.class) {
  20.                   if(arr[i]==0)
  21.                   {
  22.                           int number = (int)(Math.random()*10+1);
  23.                           arr[index] = number;
  24.                           System.out.println(arr[index]+":::::::::::b");
  25.                           index++;
  26.                   }
  27.                   
  28.    }
  29.   }  
  30. }
  31. }
复制代码






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2