Java thread pool application, java Thread Pool
The Executors tool class is used to create Java thread pools and timers.
NewFixedThreadPool: Creates a thread pool that can reuse a fixed number of threads and runs these threads in a shared unbounded queue. In any sense, in mostNThreadsThe thread is in the active state of the processing task. If an additional task is submitted when all threads are active, the additional task will wait in the queue before there is an available thread. If any thread is terminated due to a failure during the execution before it is disabled, a new thread will execute subsequent tasks (if needed) in place of it ). ExplicitlyClose
Previously, the thread in the pool will always exist.
Create a fixed thread pool to execute 10 tasks:
Instance:
1 ExecutorService threadPool = Executors.newFixedThreadPool(3); 2 for (int j = 0; j < 10; j++) { 3 final int task = j; 4 threadPool.execute(new Runnable() { 5 @Override 6 public void run() { 7 for (int i = 0; i < 10; i++) { 8 try { 9 Thread.sleep(200);10 } catch (InterruptedException e) {11 // TODO Auto-generated catch block12 e.printStackTrace();13 }14 System.out.println(Thread.currentThread().getName()+"is looping of "+ i +" task of "+task);15 }16 17 }18 });19 }
NewCachedThreadPool creates a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. CallExecuteThe previously constructed thread will be reused (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can useThreadPoolExecutor
Constructor creates a thread pool with similar properties but different details (such as timeout parameters.
Create a cache pool with 10 threads to execute 10 tasks
Instance:
1 ExecutorService threadPool = Executors.newCachedThreadPool(); 2 for (int j = 0; j < 10; j++) { 3 final int task = j; 4 threadPool.execute(new Runnable() { 5 @Override 6 public void run() { 7 for (int i = 0; i < 10; i++) { 8 try { 9 Thread.sleep(200);10 } catch (InterruptedException e) {11 // TODO Auto-generated catch block12 e.printStackTrace();13 }14 System.out.println(Thread.currentThread().getName()+"is looping of "+ i +" task of "+task);15 }16 17 }18 });19 }
NewSingleThreadExecutor creates an Executor that uses a single worker thread and runs this thread in an unbounded queue mode. (Note: If this single thread is terminated because of a failure during the execution before it is disabled, a new thread will execute subsequent tasks in place of it if needed ). The tasks can be executed sequentially, and no threads are active at any given time. Equivalent to otherNewFixedThreadPool (1)Different, you can use other threads without re-configuring the execution program returned by this method.
Create a thread to execute ten tasks (it can be used to re-execute a dead thread, but it actually starts a new thread)
Instance:
1 ExecutorService threadPool = Executors.newSingleThreadExecutor(); 2 for (int j = 0; j < 10; j++) { 3 final int task = j; 4 threadPool.execute(new Runnable() { 5 @Override 6 public void run() { 7 for (int i = 0; i < 10; i++) { 8 try { 9 Thread.sleep(200);10 } catch (InterruptedException e) {11 // TODO Auto-generated catch block12 e.printStackTrace();13 }14 System.out.println(Thread.currentThread().getName()+"is looping of "+ i +" task of "+task);15 }16 17 }18 });19 }
Difference between shutdown and shutdownNow
Shutdown: Start and close the task in sequence. Execute the previously submitted task, but do not accept the new task. If it is disabled, the call has no other effect.
ShutdownNow: attempts to stop all ongoing active tasks, pause processing pending tasks, and return to the list of pending tasks. It cannot be guaranteed that the task being processed can be stopped, but it will try its best. For exampleThread.interrupt()
To cancel the typical implementation, so any task that cannot respond to the interruption may never be terminated.
ScheduledExecutorService thread pool timer.ScheduleMethod To create a task with various delays, and return a task object that can be used to cancel or check the execution.ScheduleAtFixedRateAndScheduleWithFixedDelayMethod To create and execute some tasks that have been running regularly before cancellation.
Schedule creates and executes one-time operations enabled after a given delay.
1 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); 2 for (int i = 0; i < 10; i++) { 3 final int timer = i;*/ 4 /*scheduledThreadPool.schedule(new Runnable() { 5 @Override 6 public void run() { 7 try { 8 Thread.sleep(20); 9 } catch (InterruptedException e) {10 // TODO Auto-generated catch block11 e.printStackTrace();12 }13 System.out.println(Thread.currentThread().getName()+" " +timer);14 }15 }, 2, TimeUnit.SECONDS);
ScheduleAtFixedRate creates and executes a scheduled operation that is enabled for the first time after a given initial delay. Subsequent operations have a given cycle, that isInitialDelayAnd then runInitialDelay + periodAnd thenInitialDelay + 2 * periodAnd so on. If any execution of the task encounters an exception, subsequent execution will be canceled. Otherwise, the task can only be terminated by canceling or terminating the program. If any execution of this task takes longer than its cycle, the subsequent execution will be postponed, but will not be executed at the same time.
1 scheduledThreadPool.scheduleAtFixedRate(new Runnable() { 2 3 @Override 4 public void run() { 5 try { 6 Thread.sleep(20); 7 } catch (InterruptedException e) { 8 // TODO Auto-generated catch block 9 e.printStackTrace();10 }11 System.out.println(Thread.currentThread().getName());12 }13 }, 2, 3, TimeUnit.SECONDS);
ScheduleWithFixedDelay creates and executes a scheduled operation that is enabled for the first time after a given initial delay. Then, there is a given delay between each execution termination and the next execution start. If any execution of the task encounters an exception, subsequent execution will be canceled. Otherwise, the task can only be terminated by canceling or terminating the program.
1 scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { 2 3 @Override 4 public void run() { 5 try { 6 Thread.sleep(20); 7 } catch (InterruptedException e) { 8 // TODO Auto-generated catch block 9 e.printStackTrace();10 }11 System.out.println(Thread.currentThread().getName());12 }13 }, 2, 3, TimeUnit.SECONDS);