事实不像想象中的那样,实践,体会的才深。
被覆盖输出
list.size()=1937 //73个元素被覆盖// 如果size==2000,再试一次直到size <2000
p=1508,n=1510 //1509被覆盖
p=1575,n=1577 //1509被覆盖
检查全部输出:
1506-3001-1507-1508-3002-1510,发现1509被覆盖了。
LinkList,不仅会少,还会nullPointer,因为本身它的last.next==null,多线程,会让被覆盖的元素.next==null,next.next时就会nullPointer了。
import java.util.ArrayList;
import java.util.List;
/**
* @author timeriver.wang
* @date 2014-04-18 8:59:08 AM
*/
public class Test {
public static void main( String[] args ) {
new Test().work();
}
public void work(){
List<Integer> list = new ArrayList<Integer>(2000);
TT tt = new TT(list);
Thread t1 = new Thread( tt, "t-1" );
Thread t2 = new Thread( tt, "t-2" );
t1.start();
t2.start();
//尽量保证两个线程的方法体同时开始执行
tt.started =true;
//确保线程t-1,t-2运行结束
try {
Thread.sleep( 10000 );
}
catch ( InterruptedException e ) {
}
printSeq( list );
printAll( list );
}
private class TT implements Runnable{
private List<Integer> list;
public volatile boolean started;
public TT(List<Integer> list){
this.list = list;
}
@Override
public void run() {
while(true){
if(started){
if(Thread.currentThread().getName().contains( "-1" )){
System.out.println(Thread.currentThread().getName()+list.size());
for(int i=1000;i<2000;i++){
list.add( i );
}
}else{
System.out.println(Thread.currentThread().getName()+list.size());
for(int i=3000;i<4000;i++){
list.add( i );
}
}
break;
}
}
}
}
private void printAll(List<Integer> list){
System.out.println("############################");
System.out.println("输出全部");
System.out.println("############################");
System.out.println("list.size()="+list.size());
for(int i=0;i<list.size();i++){
System.out.print(list.get( i )+"-");
if(i%100 == 0){
System.out.println();
}
}
}
private void printSeq(List<Integer> list){
System.out.println("############################");
System.out.println("顺序被覆盖的元素输出");
System.out.println("############################");
System.out.println("list.size()="+list.size());
int p = 999;
int n = 0;
for(int i=0;i<list.size();i++){
n = list.get(i );
if(n == p+1){
p = n;
}else if((n > p+1) && n < p + 1000){
System.out.println("p="+p+",n="+n);
p=n;
}
}
}
}