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();
var threadList = new ArrayList();
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 arrayList; //volatile不能保证lock
public HttpThread(ArrayList arrayList) {
this.arrayList = arrayList;
}
public void run() {
synchronized(arrayList) { //需要在操作存储对象时 对存储对象上锁
arrayList.add(get());
}
}
public String get(){
double rand = Math.random();
return String.valueOf(rand);
}
}