多线程数量的问题,一般情况下,多线程数量要等于机器CPU核数-1.
实例1:
解决问题:如何让n个线程顺序遍历含有n个元素的List集合
1 import java.util.ArrayList; 2 import java.util.List; 3 import org.apache.commons.lang3.ArrayUtils; 4 5 public class Test_4 { 6 /** 7 * 多线程处理list 8 * 9 * @param data 数据list 10 * @param threadNum 线程数 11 */ 12 public synchronized void handleList(List<String> data, int threadNum) { 13 int length = data.size(); 14 int tl = length % threadNum == 0 ? length / threadNum : (length 15 / threadNum + 1); 16 17 for (int i = 0; i < threadNum; i++) { 18 int end = (i + 1) * tl; 19 HandleThread thread = new HandleThread("线程[" + (i + 1) + "] ", data, i * tl, end > length ? length : end); 20 thread.start(); 21 } 22 } 23 24 class HandleThread extends Thread { 25 private String threadName; 26 private List<String> data; 27 private int start; 28 private int end; 29 30 public HandleThread(String threadName, List<String> data, int start, int end) { 31 this.threadName = threadName; 32 this.data = data; 33 this.start = start; 34 this.end = end; 35 } 36 37 public void run() { 38 List<String> subList = data.subList(start, end)/*.add("^&*")*/; 39 System.out.println(threadName+"处理了"+subList.size()+"条!"); 40 } 41 42 } 43 44 public static void main(String[] args) { 45 Test_4 test = new Test_4(); 46 // 准备数据 47 List<String> data = new ArrayList<String>(); 48 for (int i = 0; i < 6666; i++) { 49 data.add("item" + i); 50 } 51 test.handleList(data, 5); 52 System.out.println(ArrayUtils.toString(data)); 53 } 54 }