1、采用线程池的方式,实现有返回值的Callable<V>线程接口
package com.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadCountByExecutor {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService cxecutorService = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(cxecutorService);
for (int i = 0; i < 4; i++) {
cs.submit(new Worker(i+1));
}
cxecutorService.shutdown();
int total = 0;
for (int i = 0; i < 4; i++) {
total += cs.take().get();
}
System.out.println("所有线程已完成->>>>>" + total);
}
static class Worker implements Callable<Integer> {
private int type;
public Worker(int type) {
this.type = type;
}
@Override
public Integer call() throws Exception {
if (type == 1) {
System.out.println("统计C完毕");
return 1;
} else if (type == 2) {
Thread.sleep(10000);
System.out.println("统计D完毕");
return 2;
} else if (type == 3) {
Thread.sleep(5000);
System.out.println("统计E完毕");
return 3;
} else if (type == 4) {
System.out.println("统计F完毕");
return 4;
} else {
System.out.println("逻辑出错");
return null;
}
}
}
}
2、采用java.util.concurrent包下的CountDownLatch类来实现
package com.thread;
import java.util.concurrent.CountDownLatch;
public class TestCountFirthThread {
public static void main(String[] args) {
try {
CountDownLatch latch = new CountDownLatch(2);
Thread work1 = new StatisticalThread(latch, 2000, "work1");
Thread work2 = new StatisticalThread(latch, 5000, "work2");
work1.start();
work2.start();
latch.await();
System.out.println("finsh");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class StatisticalThread extends Thread {
CountDownLatch latch;
int waitTime;
String threadName;
public StatisticalThread(CountDownLatch latch, int waitTime, String threadName) {
super();
this.latch = latch;
this.waitTime = waitTime;
this.threadName = threadName;
}
@Override
public void run() {
try {
System.out.println("statisticalThread " + threadName + " start");
Thread.sleep(waitTime);
System.out.println("statisticalThread " + threadName + " finsh");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}