【发布时间】:2013-12-06 04:51:02
【问题描述】:
我是 Java 新手,我正在尝试这个。我有方法,我希望并行运行该方法。我希望应该有 10 个线程调用该方法并获得它们的结果。
我为此使用Callable 和Executors。我将线程池创建为:
ExecutorService executor = Executors.newFixedThreadPool(10);
当我这样做时:
executor.invokeAll(taskList);
在 10 个线程中,只有 1 个线程被从投票中取出。我只打印了这个:
The current thread is pool-1-thread-1
但我希望应该有 10 个类似的 println 语句。
这里是完整的代码:
import java.util.concurrent.Callable;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
public class Parallel
{
public static void main(String args[])
{
Learning l = new Learning();
l.message = "1st Object";
l.testThread();
}
}
//this class deals with threads
class Learning
{
public String message;
public void setMessage(String message)
{
this.message = message;
}
//contains the code where
public void testThread()
{
//create a callable for each method
Callable<String> callable1 = new Callable<String>()
{
@Override
public String call() throws Exception
{
System.out.println("The current thread is " + Thread.currentThread().getName());
return method1();
// return null;
}
};
//add to a list
List<Callable<String>> taskList = new ArrayList<Callable<String>>();
taskList.add(callable1);
//create a pool executor with 10 threads
ExecutorService executor = Executors.newFixedThreadPool(10);
try
{
List<Future<String>> futureList = executor.invokeAll(taskList);
}
catch (InterruptedException ie)
{
}
}
//put your code here!
private String method1()
{
return Thread.currentThread().getName();
}
}
我在这里遗漏了什么吗?
【问题讨论】:
-
我希望同一个 callable 应该运行 10 次。那是来自线程池。
标签: java multithreading executorservice