黑马程序员技术交流社区

标题: 线程同步的问题 [打印本页]

作者: 在学野马    时间: 2014-9-30 09:49
标题: 线程同步的问题
本帖最后由 在学野马 于 2014-9-30 17:25 编辑
  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. }
复制代码
上面注释的地方帮忙解答下还有为什么先执行下面的代码

作者: 面具猴    时间: 2014-9-30 10:31
运行结果是这样吗?

作者: 在学野马    时间: 2014-9-30 11:22
面具猴 发表于 2014-9-30 10:31
运行结果是这样吗?

恩 是这样




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