多个线程对list操作,每个线程处理list中的每一段数据
比如,线程1处理0-100的数据,线程2处理100-200的数据
class A{ public static void main(String[] args){ List<String> scheList = new ArrayList<>(); scheList.add("1"); scheList.add("2"); scheList.add("3"); scheList.add("4"); scheList.add("5"); scheList.add("6"); scheList.add("7"); scheList.add("8"); scheList.add("9"); //每个线程一次处理的数量 int num = 2; //线程数量 int threadnum=4; int j = 0; int k = j+num; ArrayList<Thread> threads = new ArrayList<>(); while (true){ for (int i = 0; i < threadnum; i++) { if (k>scheList.size()){ k=scheList.size(); }
//主线程将list切分交给每一个线程处理 List<String> strings1 = scheList.subList(j, k); int finalK = k; threads.add(new Thread(new Runnable() { @Override public void run() { try { System.out.println(strings1); }catch (Exception e){ System.out.println(e); } } })); //如果list已经完了,不在创建线程 if (k==scheList.size()){ break; } //当先线程数量-1 if (i<threadnum-1){ j=k; k = j+num; } } for(Thread t:threads){ t.start(); } for(Thread t:threads){ try { t.join(); }catch (Exception e){ System.out.println(e.getMessage()); } } threads.clear(); if (k==(scheList.size())){ break; } j=k; k = j+num; } System.out.println("结束"); } }