Packagethree;Importjava.util.LinkedList;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** * This method has no return value and cannot receive the final processing result **/ Public classmyexecutors {Private Staticlinkedlist<integer> list =NewLinkedlist<integer>(); Public Static voidMain (string[] args)throwsinterruptedexception { for(inti = 0; I < 100; i++) {list.add (i); } //Create a thread poolExecutorservice Executorservice = Executors.newfixedthreadpool (90); for(Integer every:list) {Executorservice.execute (NewRunnable () {@Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ " " +every); } }); } System.out.println ("------------------------------------------"); //end thread After task execution finishesExecutorservice.shutdown (); }}
---------------------------------------------------the following class is written by a smart Netizen, Has a return value--------------------------------------------------------------------------
PackageFour ;Importjava.util.ArrayList; Importjava.util.List; Importjava.util.concurrent.Callable; ImportJava.util.concurrent.ExecutorService; Importjava.util.concurrent.Executors; Importjava.util.concurrent.Future; Public classCunsumerlist { Public Static voidMain (string[] args) {Try{List<String> list =NewArraylist<>(); for(inti = 0; I < 100; i++) {List.add (i+ ","); } System.out.println (NewCunsumerlist (). LIST2STR (List, 5)); } Catch(Exception e) {e.printstacktrace (); } } /*** This will know the result of the thread's processing, because there is a return value *@paramlist *@paramNthreads *@return * @throwsException*/ PublicString list2str (list<string> List,Final intNthreads)throwsException {if(List = =NULL||List.isEmpty ()) { return NULL; } stringbuffer ret=NewStringBuffer (); intSize =list.size (); Executorservice Executorservice=Executors.newfixedthreadpool (nthreads); List<Future<String>> futures =NewArraylist<future<string>>(nthreads); for(inti = 0; i < nthreads; i++) { Finallist<string> sublist = list.sublist (Size/nthreads * I, size/nthreads * (i + 1))); Callable<String> task =NewCallable<string>() {@Override PublicString Call ()throwsException {System.out.println (Thread.CurrentThread (). GetName ()); StringBuffer SB=NewStringBuffer (); for(String str:sublist) {sb.append (str); } returnsb.tostring (); } }; Futures.add (Executorservice.submit (Task)); } for(future<string>future:futures) {Ret.append (Future.get ()); } executorservice.shutdown (); returnret.tostring (); } }
Multi-threaded batching of values within a list