zoukankan      html  css  js  c++  java
  • java 多线程数据同步

    import java.util.ArrayList;
    
    /*
     * This Java source file was generated by the Gradle 'init' task.
     */
    public class App {
    
        public static void main(String[] args) throws InterruptedException {
            var arrayList = new ArrayList<String>();
            var threadList = new ArrayList<Thread>();
            var httpThread = new HttpThread(arrayList);
    
            for (int i = 0; i < 100; i++) {
                var thread = new Thread(httpThread);
                threadList.add(thread);
                thread.start();
            }
    
            for (Thread t : threadList) {
                t.join();
            }
    
            System.out.println("length is " + arrayList.size());
        }
    }
    
    class HttpThread implements Runnable {
    
        private volatile ArrayList<String> arrayList; //volatile不能保证lock
    
        public HttpThread(ArrayList<String> arrayList) {
            this.arrayList = arrayList;
        }
    
        public void run() {
            synchronized(arrayList) { //需要在操作存储对象时 对存储对象上锁
                arrayList.add(get());
            }
        }
    
        public String get(){
            double rand = Math.random();
            return String.valueOf(rand);
        }
    }
    

      

  • 相关阅读:
    第八次作业
    微信用户体验
    •设计一款给爸爸妈妈用的手机
    对类的继承
    必应词典
    第二次作业二
    第二次作业
    我想搞的软工
    数字签名
    C++的学习心得
  • 原文地址:https://www.cnblogs.com/a-flydog/p/9882923.html
Copyright © 2011-2022 走看看