java - How to run different methods parallely -
i have 1 java method contains 5 different internal methods. performance improvement, want call these methods parallely.
e.g. run method1, method2, ... method5 parallel using thread.
private void getinformation() throws sqlexception, classnotfoundexception, namingexception { method1(); method2(); method3(); method4(); method5(); }
but these 5 methods have different business logic.
do this:
- for each method, create callable object wraps method.
- create executor (a fixed thread pool executor should fine).
- put callables in list , invoke them executor
- iterate on each future returned executor, wait thread complete, , results. here's simple example:
public void testthread() { //create callable 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 list list<callable<void>> tasklist = new arraylist<callable<void>>(); tasklist.add(callable1); tasklist.add(callable2); tasklist.add(callable3); //create pool executor 3 threads executorservice executor = executors.newfixedthreadpool(3); try { //start threads list<future<void>> futurelist = executor.invokeall(tasklist); for(future<void> voidfuture : futurelist) { try { //check status of each future. block until task //completes or time expires voidfuture.get(100, timeunit.milliseconds); } catch (executionexception e) { system.err.println("error executing task " + e.getmessage()); } catch (timeoutexception e) { system.err.println("timed out executing task" + e.getmessage()); } } } catch (interruptedexception ie) { //do if care interruption; } } private void method1() { system.out.println("method1"); } private void method2() { system.out.println("method2"); } private void method3() { system.out.println("method3"); }
make sure each method not share state (like common mutable field in same class) or may unexpected results. oracle provides a introduction java executors. also, this book awesome if doing kind of threading in java.
Comments
Post a Comment