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