1.需要一個執行緒類
package com.cdncp.testautomation.control.conf; import org.apache.commons.lang.ArrayUtils; import java.util.ArrayList; import java.util.List; public class HandleThread extends Thread{ private String threadName; private List<String> data; public HandleThread(String threadName, List<String> data) { this.threadName = threadName; this.data = data; } public void run() { // TODO 這裡處理資料 // data.subList(start, end).add("^&*"); System.out.println(threadName); System.out.println(data); } }
2.需要一個呼叫類
package com.cdncp.testautomation.control.conf; import io.swagger.models.auth.In; import java.util.ArrayList; import java.util.List; public class Test_4 { /** * 多執行緒處理list * * @param data 資料list * @param threadNum 執行緒數 */ public synchronized void handleList(List<String> data, int threadNum) { int len=data.size(); // System.out.println((double)len/threadNum); int interval= (int)Math.ceil((double)len/threadNum); System.out.println("interval:"+interval); for (int i = 0; i < threadNum; i++) { // System.out.println("AA:"+i*interval); // System.out.println("BB:"+(interval*(i+1)-1)); int end=interval*(i+1); HandleThread thread = new HandleThread("執行緒[" + (i + 1) + "] ", data.subList(i*interval,end > len? len:end)); thread.start(); } } public static void main(String[] args) { Test_4 test = new Test_4(); // 準備資料 List<String> data = new ArrayList<String>(); for (int i = 0; i < 50; i++) { data.add("item" + i); } test.handleList(data, 6); // System.out.println(ArrayUtils.toString(data)); } }