package com.gray.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThreadTest {
public static void main(String[] args) throws Exception {
// 开始时间
long start = System.currentTimeMillis();
// 模拟数据List
List list = new ArrayList();
for (int i = 0; i < 3000; i++) {
list.add(i + "");
}
ExecutorService exec = Executors.newFixedThreadPool(3);
CountDownLatch doneSignal = new CountDownLatch(3);
exec.execute(new PoiWriter(doneSignal,list,0,999));
exec.execute(new PoiWriter(doneSignal,list,1000,1999));
exec.execute(new PoiWriter(doneSignal,list,2000,2999));
doneSignal.await();
exec.shutdown();
System.out.println("执行任务消耗了 :" + (System.currentTimeMillis() - start) + "毫秒");
}
protected static class PoiWriter implements Runnable {
private CountDownLatch doneSignal;
private List list;
private int start;
private int end;
public PoiWriter(CountDownLatch doneSignal,List list, int start, int end) {
this.doneSignal = doneSignal;
this.start = start;
this.list = list;
this.end = end;
}
@Override
public void run() {
try {
for (int i = start; i <= end ;i++) {
list.set(i, Thread.currentThread().getName() +"<--------->" + list.get(i));
System.out.println(list.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
doneSignal.countDown();
}
}
}
}