方法1:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(100);
ExecutorService e = Executors.newFixedThreadPool(100);
for (int i = 0; i < 100; i++) {
e.execute(new A(doneSignal));
}
doneSignal.await();// wait for all to finish
System.out.println("OK!");
e.shutdown();
}
}
class A implements Runnable {
private CountDownLatch doneSignal;
public A(CountDownLatch doneSignal) {
this.doneSignal = doneSignal;
}
public void run() {
System.out.println("test");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
doneSignal.countDown();
}
}
方法2:
ExecutorService exec = Executors.newCachedThreadPool();
List<ImageUploadRunnable> tasks = new ArrayList<ImageUploadRunnable>();
tasks.add(new ImageUploadRunnable(180, savefile,url));
tasks.add(new ImageUploadRunnable(100, savefile,url));
tasks.add(new ImageUploadRunnable(60, savefile,url));
tasks.add(new ImageUploadRunnable(30, savefile,url));
List<Future<String>> futureList = exec.invokeAll(tasks, 8l, TimeUnit.SECONDS);
//
for (int i = 0, size = futureList.size(); i < size; i++) {
Future<String> fu = futureList.get(i);
String s = fu.get(3l, TimeUnit.SECONDS);
System.out.println(s);
}
exec.shutdown();
public class ImageUploadRunnable implements Callable<String> {
private File file;
private int num;
private String url;
// private CountDownLatch doneSignal;
public ImageUploadRunnable(int num, File file, String url){
this.num = num;
this.file = file;
// this.doneSignal = doneSignal;
this.url = url;
}
public String call() throws Exception {
String result = "aaaa";
return result;
}
}
方法1:转自:http://hi.baidu.com/renciabc/item/f188401acdfa51e45e53b124
主要用的是CountDownLatch 的特性
方法2:主要用的是exec.invokeAll