public class SynCountDownLatchTest {
public static void main(String[] args) {
List<String> list = Lists.newArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
//线程数
int synCount = 2;//每个线程处理的个数
int listSize = list.size();//列表总个数
int synSize = (listSize/synCount )+1;//要启几个线程
CountDownLatch beginCount = new CountDownLatch(1);
CountDownLatch endCount = new CountDownLatch(synSize);
ExecutorService pool = Executors.newFixedThreadPool(2);
for(int i =0; i<synSize; i++){
if(i+1 == synSize){
List<String> subList = list.subList(i*synCount,listSize);
SynCountDownLatchRunnableTest synRun = new SynCountDownLatchRunnableTest(subList,beginCount,endCount);
// new Thread(synRun).start();
pool.execute(synRun);
}else {
List<String> subList = list.subList(i*synCount,(i+1)*synCount);
SynCountDownLatchRunnableTest synRun = new SynCountDownLatchRunnableTest(subList,beginCount,endCount);
// new Thread(synRun).start();
pool.execute(synRun);
}
}
try {
System.out.println("main .....");
beginCount.countDown();
endCount.await();
System.out.println("main thread on");
} catch (InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
}
}
public class SynCountDownLatchRunnableTest implements Runnable {
private List<String> listData = null;
private CountDownLatch beginCount = null;
private CountDownLatch endCount = null;
public SynCountDownLatchRunnableTest(List<String> listData, CountDownLatch beginCount, CountDownLatch endCount){
this.listData = listData;
this.beginCount = beginCount;
this.endCount = endCount;
}
@Override
public void run() {
try {
beginCount.await();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getId()+"数字"+listData.toString());
endCount.countDown();
}catch (Exception e){
e.printStackTrace();
}
}
}