JDK multi-task execution framework (Executor framework) and jdkexecutor

Source: Internet
Author: User

JDK multi-task execution framework (Executor framework) and jdkexecutor
Common Executor Methods

To better control multithreading, JDK provides a thread framework Executor to help developers effectively control threads. They are all in the java. util. concurrent package and are the core of the JDK development kit. There is an important class: Executors, which plays the role of this thread factory. We can use Executors to create thread pools with specific functions.

View their source code:

Public static ExecutorService newFixedThreadPool (int nThreads) {return new ThreadPoolExecutor (nThreads, nThreads, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> ();} public static ExecutorService newSingleThreadExecutor () {return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1, 1, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> ();} public static ExecutorService newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer. MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue <Runnable> ();} public static synchronized newScheduledThreadPool (int corePoolSize, ThreadFactory threadFactory) {return new partition (corePoolSize, threadFactory);} public partition (int corePoolSize, threadFactory threadFactory) {// here, super is the ThreadPoolExecutor class super (corePoolSize, Integer. MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue (), threadFactory );}
View Code

From the source code, we can see that they are all constructed by ThreadPoolExecutor.

ThreadPoolExecutor Constructor

ThreadPoolExecutor (

Int corePoolSize, // number of core threads, number of instantiated threads when the thread pool is just initialized

Int maximumPoolSize, // maximum number of threads

Long keepLongTime, // idle time, out-of-date recycling

TimeUnit unit, // time unit

BlockingQueue <Runable> worker, // thread hold

ThreadFactory threadFactory,

RejectExecuteHandle handle // Method for rejecting execution

)

Therefore, the above methods mainly execute different behaviors based on different parameters. The newScheduleThreadPool method is a little more complex. Its method value is ScheduledExecutorService.

ScheduledExecutorService has two methods: scheduleWithFixedDelay and scheduleAtFixedRate.

1. The scheduleAtFixedRate method executes a plan (task) at a fixed frequency, that is, to execute a plan at a fixed frequency, which is not affected by the execution time of the plan. It will be executed in time. It is not affected by the scheduled execution time.
2. scheduleWithFixedDealy, after a relatively fixed delay, execute a plan (task), that is, no matter how long a task is executed, after the execution is complete, I will delay the specified time for execution. It is affected by the scheduled execution time.

class Temp extends Thread {    public void run() {        try {            System.out.println( new Date().toString() + "..run start");            Thread.sleep(3000);            System.out.println( new Date().toString() + "...run end");        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}public class ScheduledJob {        public static void main(String args[]) throws Exception {            Temp command = new Temp();        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);        System.out.println(new Date().toString() + "...start");        //scheduler.scheduleWithFixedDelay(command, 5, 2, TimeUnit.SECONDS);        scheduler.scheduleAtFixedRate(command, 5, 2, TimeUnit.SECONDS);    }}
View Code

Execution result of scheduleAtFixedRate:The execution of the run method is delayed by 5 seconds, and the execution of the run method is 3 seconds, which exceeds the specified interval of 2 seconds. Therefore, after the execution of the first run method, the second run method is executed immediately.

Tue Feb 06 15:48:01 CST 2018...startTue Feb 06 15:48:06 CST 2018..run startTue Feb 06 15:48:09 CST 2018...run endTue Feb 06 15:48:09 CST 2018..run startTue Feb 06 15:48:12 CST 2018...run endTue Feb 06 15:48:12 CST 2018..run start

Execution result of scheduleWithFixedDealy:The run method is delayed for 5 seconds, and the run method is executed for 3 seconds, which exceeds the specified interval of 2 seconds. However, after waiting for 2 seconds, then the second run method is executed.

Tue Feb 06 15:53:04 CST 2018...startTue Feb 06 15:53:10 CST 2018..run startTue Feb 06 15:53:13 CST 2018...run endTue Feb 06 15:53:15 CST 2018..run startTue Feb 06 15:53:18 CST 2018...run endTue Feb 06 15:53:20 CST 2018..run startTue Feb 06 15:53:23 CST 2018...run end
Custom Thread Pool

If the Executors factory class cannot meet our needs, you can create a thread pool by yourself. When you create a thread pool by yourself, this constructor is critical to the queue type:

Use a queue (ArrayBlockingQueue): If a new task needs to be executed, if the actual number of threads in the thread pool is smaller than corePoolSize, the thread is created first. If the number is greater than corePoolSize, the task is added to the queue for execution, if the queue is full, a row creation thread is created when the total number of threads is not greater than maximumPoolSize. If the number of threads is greater than maximumPoolSize, a denial policy is executed.
Use unbounded blockingqueue ):The unbounded task queue does not fail to join the queue unless the system resources are exhausted. When there is a new task and the number of threads in the system is smaller than corePoolSize, the new thread will execute the task. When the number of threads reaches corePoolSize, it will not continue to increase. If new tasks are added in the future, without idle thread resources, the task directly enters the queue for waiting. If the speed difference between task creation and processing is large, the unbounded queue will keep increasing rapidly until the system memory is exhausted. Note: maximumPoolSize does not work in Unbounded queues.
JDK rejection policy:
AbortPolicy: directly throws an exception. The organizational system works normally. CallerRunsPolicy: as long as the thread pool is not closed, this policy runs the currently discarded task directly in the caller's thread.
DiscardOldestPolicy: discard the oldest request and try to submit the current task again.
DiscardPolicy: discard tasks that cannot be processed without any processing.
You can implement the RejectedExecutionHandler interface if you need to customize a denial policy.

Example of a queue
Public class UseThreadPoolExecutor1 {public static void main (String [] args) {/*** when using a bounded queue, if a new task needs to be executed, if the actual number of threads in the thread pool is smaller than corePoolSize, the thread is created first. * If the number is greater than corePoolSize, the task is added to the queue. * If the queue is full, A new thread is created when the total number of threads is not greater than maximumPoolSize. * if the number of threads is greater than maximumPoolSize, a denial policy is executed. Or other custom methods. **/ThreadPoolExecutor pool = new ThreadPoolExecutor (1, // coreSize 2, // MaxSize 60, // 60 TimeUnit. SECONDS, new ArrayBlockingQueue <Runnable> (3) // specify a queue (bounded Queue) // new queue blockingqueue <Runnable> () //, new MyRejected ()//, new DiscardOldestPolicy (); MyTask mt1 = new MyTask (1, "Task 1"); MyTask mt2 = new MyTask (2, "Task 2 "); myTask mt3 = new MyTask (3, "Task 3"); MyTask mt4 = new MyTask (4, "Task 4"); MyTask mt5 = new MyTask (5, "Task 5"); MyTask mt6 = new MyTask (6, "Task 6"); pool.exe cute (mt1); pool.exe cute (mt2); pool.exe cute (mt3 ); pool.exe cute (mt4); pool.exe cute (mt5); pool.exe cute (mt6); pool. shutdown ();}}
View Code

Only the first four tasks are executed.(Do not execute the Task 5 or 6 First)

run taskId =1run taskId =2run taskId =3run taskId =4

It is executed one by one because it is immediately executed when the first thread comes (coreSize =1), When the next three threads come, they will be added to the queue (new ArrayBlockingQueue <Runnable> (3))

Only the first five tasks are executed.

run taskId =1run taskId =5run taskId =2run taskId =3run taskId =4

It is executed by two tasks because the size (3) of the queue is exceeded when the fifth task comes, but the total number of threads is smaller than MaxSize (2 ), therefore, Task 5 and Task 1 are executed together, and then two will be taken from the queue for execution.

Execute the remaining task

run taskId =1Exception in thread "main" run taskId =5java.util.concurrent.RejectedExecutionException: Task 6 rejected from java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 2, active threads = 2, queued tasks = 3, completed tasks = 0]    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)    at com.bjsxt.height.concurrent018.UseThreadPoolExecutor1.main(UseThreadPoolExecutor1.java:46)run taskId =2run taskId =3run taskId =4

When Task 6 comes, the queue is full and the total number of threads is full. This will execute the denial policy. JDK uses the AbortPolicy by default and directly throws an exception. We can also change it, I just want to comment out the same in the code.

Example of unbounded queue
Public class UseThreadPoolExecutor2 implements Runnable {private static AtomicInteger count = new AtomicInteger (0); @ Override public void run () {try {int temp = count. incrementAndGet (); System. out. println ("task" + temp); Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) throws Exception {// System. out. println (Runtime. getRuntime (). availableProcessors (); BlockingQueue <Runnable> queue = new LinkedBlockingQueue <Runnable> (); ExecutorService executor = new ThreadPoolExecutor (5, // core 10, // max 120L, // 2 fenzhong TimeUnit. SECONDS, queue); for (int I = 0; I <20; I ++) {executor.exe cute (new UseThreadPoolExecutor2 ();} Thread. sleep (1, 1000); System. out. println ("queue size:" + queue. size (); // 10 Thread. sleep (2000 );}}
View Code

Execution result:

Task 1 Task 2 Task 3 Task 4 Task 5 queue size: 15 Task 6 task 7 task 9 task 8 Task 10 task 11 Task 12 task 13 task 14 task 15 task 16 task 17 task 19 task 20 task 18

Five or five tasks are executed, and all the remaining tasks are added to the queue. The second parameter does not work and will not create 10 threads. If a queue exists, it will work.

Task code:

public class MyTask implements Runnable {    private int taskId;    private String taskName;        public MyTask(int taskId, String taskName){        this.taskId = taskId;        this.taskName = taskName;    }        public int getTaskId() {        return taskId;    }    public void setTaskId(int taskId) {        this.taskId = taskId;    }    public String getTaskName() {        return taskName;    }    public void setTaskName(String taskName) {        this.taskName = taskName;    }    @Override    public void run() {        try {            System.out.println("run taskId =" + this.taskId);            Thread.sleep(5*1000);            //System.out.println("end taskId =" + this.taskId);        } catch (InterruptedException e) {            e.printStackTrace();        }            }        public String toString(){        return Integer.toString(this.taskId);    }}
View Code

MyRejected code:

Public class MyRejected implements RejectedExecutionHandler {public MyRejected () {}@ Override public void rejectedExecution (Runnable r, ThreadPoolExecutor executor) {System. out. println ("custom processing .. "); System. out. println ("the current rejected task is:" + r. toString ());}}
View Code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.