Schematic thread pooling working mechanism, handwriting thread pool?

Source: Internet
Author: User

Description of each parameter of the Threadpoolexecutor constructor

Public threadpoolexecutor (int corepoolsize,//The number of core threads in the thread pool
int maximumpoolsize,//maximum allowable number of threads
Long keepalivetime,//thread is idle after the time of survival, this parameter is only useful in > Corepoolsize
Timeunit unit,//unit value for survival time
blockingqueue<runnable> workqueue,//blocking queue for saving tasks
Threadfactory threadfactory,//creates a thread factory, assigns a name to the new thread
Rejectedexecutionhandler handler)//saturation strategy, built-in 4 strategies

AbortPolicy: Direct throw exception, default;

Callerrunspolicy: Performing a task with the caller's thread

Discardoldestpolicy: Discard the oldest task in the blocking queue, the most forward task in the queue

Discardpolicy: The current task is discarded directly

And allow the big guy to achieve their own saturation strategy, the implementation of Rejectedexecutionhandler interface can be.

JDK code selection.

Step one (corresponding to figure 1th arrow, corresponding to the first if code block): thread pool threads are less than corepoolsize, a new thread is created.

Step two (corresponding to figure 2nd arrow, corresponding to the source of the second if code block): Thread pool threads equals Corepoolsize, this task will be saved to Blockingqueue.

Step three (corresponding to the figure 3rd arrow, corresponding to the source of the third if Code block): Blockingqueue is also full, thread pool threads less than maximumpoolsize when the new thread will be created again.

Step four (corresponding to figure 4th arrow, corresponding to the source of the third if Code block): Blockingqueue full, thread pool threads is equal to maximumpoolsize when the saturation policy is executed.

Interviewer: "Talk about your understanding of the thread pool", I: "silently handwritten a thread pool", the invisible Force is the most deadly.

/**
*
* Class Description: The implementation of their own thread pool
*/
public class MyThreadPool2 {
The number of default threads in the thread pool is 5
private static int work_num = 5;
Queue default task number is 100
private static int task_count = 100;

Worker Thread Group
Private workthread[] workthreads;

Task queue, as a buffer
Private final blockingqueue<runnable> Taskqueue;
Private final int worker_num;//The number of threads that the user is constructing this pool, the desired start

Create a thread pool with the number of default threads
Public MyThreadPool2 () {
This (Work_num,task_count);
}

Create a thread pool, worker_num the number of worker threads in the thread pools
Public MyThreadPool2 (int worker_num,int taskcount) {
if (worker_num<=0) worker_num = Work_num;
if (taskcount<=0) Taskcount = Task_count;
This.worker_num = Worker_num;
Taskqueue = new arrayblockingqueue<> (taskcount);
Workthreads = new Workthread[worker_num];
for (int i=0;i<worker_num;i++) {
Workthreads[i] = new Workthread ();
Workthreads[i].start ();
}
Runtime.getruntime (). Availableprocessors ();
}


To perform a task, it is simply to join the task queue and when to execute the thread pool manager decision
public void execute (Runnable task) {
try {
Taskqueue.put (Task);
} catch (Interruptedexception e) {
E.printstacktrace ();
}

}


Destroys the thread pool, which ensures that all threads are destroyed if all tasks are completed, otherwise it is not destroyed until the task is completed
public void Destroy () {
Worker thread stops working and is set to NULL
System.out.println ("Ready close pool ...");
for (int i=0;i<worker_num;i++) {
Workthreads[i].stopworker ();
Workthreads[i] = Null;//help GC
}
Taskqueue.clear ();//emptying the task queue
}

Override tostring method, return thread pool information: number of worker threads and number of completed tasks
@Override
Public String toString () {
Return "Workthread number:" + worker_num
+ "Wait task number:" + taskqueue.size ();
}

/**
* Inner class, worker thread
*/
Private class Workthread extends thread{

@Override
public void Run () {
Runnable r = null;
try {
while (!isinterrupted ()) {
R = Taskqueue.take ();
if (r!=null) {
System.out.println (GetId () + "Ready exec:" +r);
R.run ();
}
R = Null;//help GC;
}
} catch (Exception e) {
Todo:handle exception
}
}

public void Stopworker () {
Interrupt ();
}

}
}

Test class:

public class Testmythreadpool extends threadpoolexecutor{

Public Testmythreadpool (int corepoolsize, int maximumpoolsize, long keepalivetime, Timeunit unit,
Blockingqueue<runnable> WorkQueue, Rejectedexecutionhandler handler) {
Super (Corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, WorkQueue, handler);
TODO auto-generated Constructor stub
}

public static void Main (string[] args) throws Interruptedexception {
Create a thread pool of 3 threads
MyThreadPool2 t = new MyThreadPool2 (3,0);
T.execute (New MyTask ("TestA"));
T.execute (New MyTask ("Testb"));
T.execute (New MyTask ("TESTC"));
T.execute (New MyTask ("TestD"));
T.execute (New MyTask ("Teste"));
System.out.println (t);
Thread.Sleep (10000);
T.destroy ();//All threads are executed before destory
System.out.println (t);
}

Task class
Static Class MyTask implements Runnable {

private String name;
Private random R = new Random ();

Public MyTask (String name) {
THIS.name = name;
}

Public String GetName () {
return name;
}

@Override
public void Run () {//Execute task
try {
Thread.Sleep (R.nextint (1000) +2000);
} catch (Interruptedexception e) {
System.out.println (Thread.CurrentThread (). GetId () + "Sleep interruptedexception:"
+thread.currentthread (). isinterrupted ());
}
SYSTEM.OUT.PRINTLN ("task" + name + "Finish");
}
}
}

Schematic thread pooling working mechanism, handwriting thread pool?

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.