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));
本文介绍了如何使用Java中的ExecutorService来管理线程池,包括创建不同类型的线程池、提交任务及停止线程的方法。通过示例代码展示了固定大小线程池的使用,并解释了ExecutorService相较于Executor提供的额外功能。
4782

被折叠的 条评论
为什么被折叠?



