`

Executor usage

阅读更多

Executor is used to arrange thread execution. Basicly speaking, just manage, how many threads are permited to run together.

 

ExecutorService obj = Executors.newSingleThreadExecutor( ) -- only 1

ExecutorService obj = Executors.newFixedThreadPool(int poolSize) -- fix amount

ExecutorService obj = Executors.newCachedThreadPool( ) --- as many as it can

 

Code Sample

 

Executor e = Executors.newFixedThreadPool(5);

e.execute(new RunnableTask1( ));

e.execute(new RunnableTask2( )); 

e.execute(new RunnableTask3( ));

 

 

While in another aritcle, you can see that, Executors.newFixedThreadPool(5) returns a ExecutorService. Actually, ExecutorService is a subclass of Executor, and it supplies more functionalities than Executor.

 

 

 

 As far as ExecutorService is concerned, it supplies only one advanced function than Executor---how to stop the threads.

 

service.shutdownNow(); //Try to finish all Runnables(started and not started(in queue)), then, stop Executor.

service.shutdown(); //Directly stop the Executor, terminate running Runables, return back not started, yet in queue Runables.

 

There is a internal Queue maintained by ExecutorService. That's the core idea.

 

 

 ------------------------------------------------------------------------------------

Another point, Please pay attention to how they are used to different targets.

 

//FutureObject = ExecutorService.submit(Callable object);

//Executor.execut(Runnable object); //without any returns.

Future<BigInteger> prime1 = service.submit(new RandomPrimeSearch(512));

Future<BigInteger> prime2 = service.submit(new RandomPrimeSearch(512));

Future<BigInteger> prime3 = service.submit(new RandomPrimeSearch(512));

 

 

 

 

 

 

 

 


  


  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics