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);
    }
}

  

原文地址:https://www.cnblogs.com/a-flydog/p/9882923.html