JUC

List线程不安全测试

2019-11-08  本文已影响0人  秋名山车神_f776

public class ListSafeTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
   List<String> list = new ArrayList<String>();
   List<Thread> threadList = new ArrayList<Thread>();
   for(int i=0;i<5;i++){
       Thread t = new Thread(new MyThread(list));
       t.start();
       threadList.add(t);
   }
   
   for(int i=0;i<threadList.size();i++){
       try {
        threadList.get(i).join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
   
   System.out.println(list.size());
}


public static class MyThread implements Runnable{
    public List<String> list;
    public MyThread(List<String> plist){
        this.list = plist;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<50;i++){
            list.add("aa");
        }
    }
}

}

图片.png
上一篇下一篇

猜你喜欢

热点阅读