美文网首页JUC
List线程不安全测试

List线程不安全测试

作者: 秋名山车神_f776 | 来源:发表于2019-11-08 16:07 被阅读0次

    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

    相关文章

      网友评论

        本文标题:List线程不安全测试

        本文链接:https://www.haomeiwen.com/subject/ufhwbctx.html