1 Reasons for introducing thread pools
Since the life cycle of a thread includes the creation, ready, running, blocking, and destroy stages, when the number of tasks we pending is small, we can create several threads ourselves to handle the corresponding tasks, but when there are a large number of tasks, Creating and destroying threads requires a lot of overhead, and using thread pools will greatly alleviate these problems.
2 Use of thread pool
We only need to use the static method provided by the Executors class to create the corresponding thread pool:
public static ExecutorSevice newSingleThreadExecutor() public static ExecutorSevice newFixedThreadPool() public static ExecutorSevice newCachedThre adPool()
newSingleThreadExecutor returns an Executor containing a single thread. When multiple tasks are handed over to this Executor, the thread processes one task and then processes the next task. If an exception occurs in the thread, a new thread will be replaced.
newFixedThreadPool returns a thread pool containing a specified number of threads. If the number of tasks is more than the number of threads, no unexecuted tasks must wait until a task is completed.
newCachedThreadPool creates corresponding threads based on the number of tasks of the user. This thread pool will not limit the number of threads and depends entirely on the number of threads that the JVM can create, which may cause insufficient memory.
We only need to put the task to be executed into the run method, and hand over the implementation class of the Runnable interface to the execute method of the thread pool as a parameter, as shown below:
Executor executor = Executors.newSingleThreadExecutor();executor.execute(new Runnable(){ public void run(){ //Executed tasks}}If you need to pass parameters to the task, you can do it by creating an implementation class for the Runnable interface.
3. Example
(1): newSingleThreadExecutor
MyThread.java
publicclassMyThread extends Thread { @Override publicvoid run() { System.out.println(Thread.currentThread().getName() + "Execution..."); }}Test SingleThreadExecutor.javapublicclassTestSingleThreadExecutor { publicstaticvoid main(String[] args) { //Create a thread pool that can reuse fixed number of threads ExecutorService pool = Executors. newSingleThreadExecutor(); //Create a Runnable interface object, and the Thread object of course also implements the Runnable interface Thread t1 = ne w MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //Put the thread into the pool for execution pool.execute(t1); pool.execu te( t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //Close the thread pool pool.shutdown(); }} Output result
pool-1-thread-1 is executing. . . pool-1-thread-1 is executing. . . pool-1-thread-1 is executing. . . pool-1-thread-1 is executing. . . pool-1-thread-1 is executing. . .
(2): newFixedThreadPool
TestFixedThreadPool.Java
publicclass TestFixedThreadPool { publicstaticvoid main(String[] args) { //Create a thread pool that can reuse fixed number of threads ExecutorService pool = Executors.newFixedThreadPo ol(2); //Create the Runnable interface object, and the Thread object also implements Runnable Interface Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //Put the thread in Perform in the pool Execute pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //Close the thread pool pool.shutdown(); }} Output result
pool-1-thread-1 is executing. . . pool-1-thread-2 is executing. . . pool-1-thread-1 is executing. . . pool-1-thread-2 is executing. . . pool-1-thread-1 is executing. . .
(3): newCachedThreadPool
TestCachedThreadPool.java
publicclass TestCachedThreadPool { publicstaticvoid main(String[] args) { //Create a thread pool that can reuse fixed number of threads ExecutorService pool = Executors.newCachedThread Pool(); //Create the Runnable interface object, and the Thread object also implements the Runnable interface Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //Put the thread into the pool Execute in pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //Close the thread pool pool.shutdown(); }} Output result:
pool-1-thread-2 is executing. . . pool-1-thread-4 is executing. . . pool-1-thread-3 is executing. . . pool-1-thread-1 is executing. . . pool-1-thread-5 is being executed. . .
(4): newScheduledThreadPool
TestScheduledThreadPoolExecutor.java
publicclass TestScheduledThreadPoolExecutor { publicstaticvoid main(String[] args) { ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecut tor(1); exec.scheduleAtFixedRate(new Runnable() {//Exception is triggered every once in a while @Override publicvoid run() { //throw new RuntimeException(); System.out.println("================================================================================================== Runna ble() {//Print the system time every once in a while, proving that the two have no influence on each other @Override publicvoid run() { System.out.println(System.nanoTime()); } }, 1000, 2000, TimeUnit.MILLISECONDS) ; }} Output result
===============================================================================================================================================================================================================================================================