用多个线程处理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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值