用多个线程处理1个List集合

  昨天发了一个提问,启动5个线程将一个List中的内容,然后将5个线程的内容拼接起来,由于时间比较急迫,自己就写了一个Demo,希望对菜鸟有参考意义。。


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ThreadTest {

	private static final int total = 100000;
	
	public static void test1() throws InterruptedException {
		List<String> datas = new ArrayList<String>(total);
		for(int i =0; i< total; i++){
			datas.add(i+"");
		}
		StringBuffer sb = new StringBuffer();
		long s = System.currentTimeMillis();
		for(int i =0; i< datas.size(); i++){
			sb.append(datas.get(i));
		}
		long e = System.currentTimeMillis();
		System.out.println("单线程执行所需时间:" +(e-s));
	}
	
	
	public static void test2() throws InterruptedException {
		List<String> datas = new ArrayList<String>(total);
		for(int i =0; i< total; i++){
			datas.add(i+"");
		}
		int threadSize = 5;
		int size = datas.size();
		int x = size / threadSize;
		StringBuffer result = new StringBuffer();
		CountDownLatch doneSignal = new CountDownLatch(threadSize);
		long s = System.currentTimeMillis();
		for(int i= 0; i< threadSize ;i++){
			int start  = i * x;
			int end = (i+1) < threadSize ? (i+1) * x :  size;
			Thread t = new Thread(new WorkerRun(doneSignal, datas, start, end, result));
			t.start();
		}
		doneSignal.await();
		long e = System.currentTimeMillis();
		System.out.println("多线程执行所需时间:" +(e-s));
	}
	
	public static void main(String[] args) throws InterruptedException {
		test1();
		test2();
	}
	
}

class WorkerRun implements Runnable{

	private final CountDownLatch doneSignal;
	
	private List<String> datas = null;
	
	private int start;
	
	private int end;
	
	private StringBuffer result = null;
	
	public WorkerRun(CountDownLatch doneSignal,List<String> datas ,int start, int end,StringBuffer result){
		this.doneSignal = doneSignal;
		this.datas = datas;
		this.start = start;
		this.end = end;
		this.result = result;
	}
	
	@Override
	public void run() {
		StringBuffer sb = new StringBuffer();
		for(int i = start; i< end ;i ++){
			String str = datas.get(i);
			sb.append(str);
		}
		result.append(sb);
		//执行完成后等待
		doneSignal.countDown();
	}
}



另外说一点,我发现多线程这样处理比单线程数据差不多慢了一倍,有点不解。也请大神指教。。

运行的结果:
单线程执行所需时间:6
多线程执行所需时间:18


你可能感兴趣的:(多线程,thread,list,集合)