Java neutralized pool simple construction

zhaozj2021-02-17  55

Java

Medium thread pool simple construction

Yang Hengxian (Yang_Hx@neusoft.com)

Now the server's application has almost all "thread pool" technology, mainly in order to improve system efficiency. Because if the server creates a thread, in a short period of time, there will be a lot of creation and destruction threading actions, resulting in the time and consumption of the server to create and destroy the thread. Treatment of actual user requests more time and resources. The thread pool is to minimize the occurrence of this situation.

Let's take a look at how to use Java to implement a thread pool. A relatively simple thread pool should include at least a thread pool manager, a working thread, task queue, task interface, and other parts. The Role of ThreadPool Manager is to create, destroy and manage the thread pool, put the work thread into the thread pool; the working thread is a thread that can loopulate the task, waiting for the task; task queue The role is to provide a buffer mechanism that will be placed in the task queue; the task interface is the interface that must be implemented in each task, mainly used to specify the entrance of the task, and the task is executed, the task is implemented. Wait, the work thread passes the execution of the interface scheduling task.

One is to use the number of fixed threads as a reference, so that the working threads of each thread are in an infinite loop, using nodify () in Java, collaboration works with Wait ().

Basic ideas are as follows:

Create all working threads when building a thread pool, and let all the work thread start running.

Public threadpool (int npoolsize) {

IF (NPOOLSIZE <= 0) {

NPOOLSIZE = default_pool_size;

}

m_threadlist = new arraylist ();

m_runlist = new linkedlist ();

For (INT i = 0; i

Workerthread Temp = New Workerthread (i 1);

m_threadlist.add (temp);

TEMP.START ();

}

}

Waiting with Wait () in the run () method of the working thread, when the thread is in the wait () state does not occupy the CPU, so all working threads are in the suspended state, waiting for the task to wake up.

The implementation is as follows:

While (true) {

SYNCHRONIZED (M_Runlist) {

While (m_runlist.isempty ()) {// Task list is a space for the space, otherwise run the task and eliminate the task in this task list

Try {

m_runlist.wait ();

}

Catch (InterruptedException E) {

}

}

R = (runnable) m_runlist.removefirst ();

//System.out.println (M_NTHREADID ": start");

IF (r == null) return;

}

Try {

R.Run ();

}

Catch (Exception E) {

}

}

The above code is the main code of a work thread. This thread will never stop, just hang, or run the task.

Introduce another method of implementation of another thread pool tomorrow.

Http://www.wds.gov.cn/upimage/200417737.rar

转载请注明原文地址:https://www.9cbs.com/read-30037.html

New Post(0)