【发布时间】:2015-08-01 09:39:50
【问题描述】:
我想并行执行一些任务,所以我在 Java 中搜索多线程,并找到了这个类,ExecutorService。我尝试了一个简单的例子,但我不确定它是否并行运行。
long startTime = System.currentTimeMillis();
List<Callable<String>> callables = new ArrayList<Callable<String>>();
ExecutorService executor = Executors.newCachedThreadPool();
callables.add(new Callable<String>() {
public String call() {
for (int i=0; i<100000; i++) {
System.out.println("i "+i);
}
return "Task 1";
}
}
);
callables.add(new Callable<String>() {
public String call() {
for (int j=0; j<100000; j++) {
System.out.println("j "+j);
}
return "Task 2";
}
}
);
callables.add(new Callable<String>() {
public String call() {
for (int k=0; k<100000; k++) {
System.out.println("k "+k);
}
return "Task 3";
}
}
);
try {
List<Future<String>> futureLst = executor.invokeAll(callables);
for (Future future : futureLst) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));
上面的代码可以正常工作并打印计数并返回字符串。上述程序执行时间为“3229”毫秒。
我把上面的程序改写如下,
long startTime = System.currentTimeMillis();
for (int i=0; i<100000; i++) {
System.out.println("i "+i);
}
for (int j=0; j<100000; j++) {
System.out.println("j "+j);
}
for (int k=0; k<100000; k++) {
System.out.println("k "+k);
}
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));
这个程序花费的时间是“3104”毫秒,比并行执行编码的时间要短。
那么我在第一个程序中做错了吗?我的第一个程序是否并行运行任务,因为我看到没有线程花费的时间更少?
【问题讨论】:
-
尝试使用 Runnable 而不是 Callable。
标签: java multithreading parallel-processing