A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

  1. import java.util.*;
  2. public class Test5 {
  3.    
  4.         /**
  5.          * @param args
  6.          */
  7.         public static void main(String[] args) {
  8.                 // TODO Auto-generated method stub
  9.    Add add=new Add();
  10.    Thread t1=new Thread(add);
  11.    Thread t2=new Thread(add);
  12.    t1.start();
  13.    t2.start();
  14.    
  15.    try {
  16.         Thread.sleep(1000);
  17. } catch (InterruptedException e) {
  18.         // TODO Auto-generated catch block
  19.         e.printStackTrace();
  20. }
  21.    System.out.println(add.list);
  22.         }

  23. }

  24. class Add implements Runnable{
  25.      int i=0;
  26.      List<Integer> list=new ArrayList<Integer>();
  27.      Random r=new Random();
  28.         public void run() {
  29.                 for (int x = 0; x < 3; x++) {
  30.                         synchronized (this) {
  31.                                 this.notify();
  32.                                 int y=r.nextInt(10);
  33.                                 System.out.println(Thread.currentThread().getName()+"......"+y);
  34.                                 list.add(y);
  35.                                 try {
  36.                                         this.wait();
  37.                                 } catch (InterruptedException e) {
  38.                                         // TODO Auto-generated catch block
  39.                                         e.printStackTrace();
  40.                                 }
  41.                         }
  42.                 }
  43. }
  44.        
  45. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马