我有一个Java方法,其中包含5种不同的内部方法。为了提高性能,我想并行调用这些方法。
例如,使用线程并行运行method1,method2,... method5。
private void getInformation() throws SQLException,
ClassNotFoundException, NamingException {
method1();
method2();
method3();
method4();
method5();
}
但是所有这5种方法都有不同的业务逻辑。
做这样的事情:
这是一个简单的例子:
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");
}
确保每个方法都不共享状态(例如同一类中的公共可变字段),否则您可能会得到意想不到的结果。Oracle为Java执行器提供了很好的介绍。另外,如果您正在使用Java进行任何形式的线程编写,那么本书都将是很棒的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句