我有一个 java 方法,其中包含 5 个不同的内部方法。为了提高性能,我想并行调用这些方法。
例如使用线程并行运行 method1、method2、... method5。
private void getInformation() throws SQLException,
ClassNotFoundException, NamingException {
method1();
method2();
method3();
method4();
method5();
}
但这5个方法都有不同的业务逻辑。
最佳答案
做这样的事情:
- 为每个方法创建一个包装该方法的 Callable 对象。
- 创建一个执行器(固定线程池执行器应该没问题)。
- 将所有 Callable 放入列表中,并使用 Executor 调用它们。
这是一个简单的例子:
public void testThread()
{
//create a callable for each method
Callable<Void> callable1 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method1();
return null;
}
};
Callable<Void> callable2 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method2();
return null;
}
};
Callable<Void> callable3 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method3();
return null;
}
};
//add to a list
List<Callable<Void>> taskList = new ArrayList<Callable<Void>>();
taskList.add(callable1);
taskList.add(callable2);
taskList.add(callable3);
//create a pool executor with 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
try
{
//start the threads and wait for them to finish
executor.invokeAll(taskList);
}
catch (InterruptedException ie)
{
//do something if you care about interruption;
}
}
private void method1()
{
System.out.println("method1");
}
private void method2()
{
System.out.println("method2");
}
private void method3()
{
System.out.println("method3");
}
确保每个方法不共享状态(如同一类中的公共(public)可变字段),否则您可能会得到意想不到的结果。 Oracle 提供 a good introduction to Java Executors .另外,this book如果您在 Java 中进行任何类型的线程处理,那真是太棒了。
关于java - 如何并行运行不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18162863/