黑马程序员技术交流社区
标题:
两个线程同时给ArrayList集合传随机值,并且是两个线程交.....
[打印本页]
作者:
明月刀割芳草
时间:
2015-8-12 22:04
标题:
两个线程同时给ArrayList集合传随机值,并且是两个线程交.....
import java.util.*;
public class Test5 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Add add=new Add();
Thread t1=new Thread(add);
Thread t2=new Thread(add);
t1.start();
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(add.list);
}
}
class Add implements Runnable{
int i=0;
List<Integer> list=new ArrayList<Integer>();
Random r=new Random();
public void run() {
for (int x = 0; x < 3; x++) {
synchronized (this) {
this.notify();
int y=r.nextInt(10);
System.out.println(Thread.currentThread().getName()+"......"+y);
list.add(y);
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2