import java.util.List;/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-09-27
* Time: 15:42
*///執行緒任務類publicclassCollectionTaskimplementsRunnable{private List<String> list;publicCollectionTask(List<String> list){this.list = list;}@Overridepublicvoidrun(){//在任務中插入名字try{
Thread.sleep(100);}catch(InterruptedException e){
e.printStackTrace();}
list.add(Thread.currentThread().getName());}}
測試類
import java.util.ArrayList;import java.util.Collections;import java.util.List;/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-09-27
* Time: 15:41
*///測試類publicclassArrayListSafetyTest{publicstaticvoidmain(String[] args){
List<String> list =newArrayList<>();//list = Collections.synchronizedList(list);
CollectionTask task =newCollectionTask(list);for(int i =0; i <50; i++){newThread(task).start();}//等待執行緒執行try{
Thread.sleep(1000);}catch(InterruptedException e){
e.printStackTrace();}//遍歷連結串列for(String str : list
){
System.out.println(str);}}}
import java.util.ArrayList;import java.util.Collections;import java.util.List;/**
* Created with IntelliJ IDEA.
* Description: If you don't work hard, you will a loser.
* User: Listen-Y.
* Date: 2020-09-27
* Time: 15:41
*///測試類publicclassArrayListSafetyTest{publicstaticvoidmain(String[] args){
List<String> list =newArrayList<>();//重點
list = Collections.synchronizedList(list);
CollectionTask task =newCollectionTask(list);for(int i =0; i <50; i++){newThread(task).start();}//等待執行緒執行try{
Thread.sleep(1000);}catch(InterruptedException e){
e.printStackTrace();}//遍歷連結串列for(String str : list
){
System.out.println(str);}}}