How to create a thread pool in Java

Source: Internet
Author: User

A thread is a major feature of Java, which can be a given sequence of instructions, a variable defined in a given method, or some shared data (a variable at the class level). In Java each thread has its own stack and program counter (PC), where the stack is used to track the thread's context (the context is the value of the current local variable when the thread executes to a point), and the program counter is used to track the instruction that the current thread is executing.

One thread cannot access the stack variable of another thread, and the thread must be in one of the following states:

1. Queued State (ready), the thread does not run immediately after the user creates a thread. When the method start () in the thread is called, the thread is queued and waits for the scheduler to turn it into a running state (Running). It can also be queued when a process is executed. If the scheduler allows, the process can be queued by invoking the method yield ().

2. Running state (Running), when the scheduler allocates CPU uptime to a thread, the thread enters the running state and starts running.

3. Wait state (waiting), a number of reasons can cause a thread to wait, such as when a thread is being paused during execution, or waiting for the completion of an I/O request to enter a waiting state.

Different threads in Java have different priorities, and high-priority threads can be scheduled to complete before a low-priority thread. If multiple threads have the same priority, Java switches between different threads. An application can set the priority of a thread by using the method SetPriority () in the thread, using method GetPriority () to get the priority of a thread.

The life cycle of a thread

The cycle can be divided into two phases: the survival (Alive) cycle and the Death (Dead) cycle, where the life cycle includes the running state (Running) and the Wait state (waiting). When a new thread is created, the thread enters the queued state (ready) and the thread enters the lifetime when the method start () in the thread is called, and its method IsAlive () always returns true until the thread enters the dead state.

Implementation of Threads

Threads can be implemented, one is to extend the Java.lang.Thread class, and the other is through the Java.lang.Runnable interface.

The Hread class encapsulates the behavior of the thread. To create a thread, you must create a new class that extends from the thread class. Because the method run () in the thread class does not provide any action, the user must override the method run () to accomplish useful work when the thread is created. The method run () is called when the method Start () in the thread is called. The following code implements the thread by extending the thread class:

Import java.awt.*;

Class sample1{

public static void Main (string[] args) {

Mythread test1=new Mythread (1);

Mythread test2=new Mythread (2);

Test1.start ();

Test2.start ();

}

}

Class Mythread extends Thread {

int id;

Mythread (int i)

{id=i;}

public void Run () {

int i=0;

while (id+i==1) {

try {sleep (1000);

} catch (Interruptedexception e) {}

}

SYSTEM.OUT.PRINTLN ("The ID is" +id);

}

5 There is no hope that a class can run in its own thread, while also extending the characteristics of some other classes, it needs to be implemented by running the Runnable interface. The runnable interface has only one method run (). Whenever you create a class that uses the Runnable interface, you must write the run () method in the class to overwrite the run () method in the interface. For example, the following code is a thread implemented through the Runnable interface:

Import java.awt.*;

Import Java.applet.Applet;

public class Bounce extends Applet implements runnable{

static int r=30;

static int x=100;

static int y=30;

Thread T;

public void Init ()

{

t = new Thread (this);

T.start ();

}

public void Run ()

{

int y1=+1;

int i=1;

int sleeptime=10;

while (true)

{

y+= (I*y);

if (Y-rgetsize (). Height)

Y1*=-1;

try{

T.sleep (Sleeptime);

}catch (Interruptedexception e) {}

}

}

}

Why use a thread pool

In Java, if a new thread is created every time a request arrives, the overhead is quite large. In practice, the amount of time and resources spent on creating and destroying threads for each server requesting the creation of a new thread may even be much more than the time and resource spent processing the actual user request. In addition to the overhead of creating and destroying threads, the active thread also consumes system resources. If you create too many threads in a single JVM, you may cause your system to be running out of resources due to excessive memory consumption or "over-switching". To prevent resource shortages, server applications need some way to limit the number of requests processed at any given moment, minimizing the number of threads that are created and destroyed, especially when some resources are expensive to create and destroy, and use existing objects to service as much as possible, which is why "pooled resources" technology.

Used to troubleshoot thread life-cycle overhead and resource-poor issues. By reusing threads on multiple tasks, the cost of thread creation is shared across multiple tasks, and the delay caused by thread creation is eliminated because the thread already exists when the request arrives. In this way, you can immediately service the request and make the application respond faster. In addition, you can prevent resource shortages by adjusting the number of threads in the thread pool appropriately. Job coordinates www.zhizuobiao.com

Create a pool of threads

Includes thread pool manager, worker thread, Task queue, task interface, and so on. The role of the thread pool manager (ThreadPool Manager) is to create, destroy, and manage the thread pool, put the worker thread into the thread pools, and the worker thread is a thread that can loop through the task, wait while there is no task, and the task queue is to provide a buffering mechanism. Put tasks that are not processed in the task queue; The task interface is the interface that each task must implement, which is used to specify the entry of the task, the finishing work after the completion of the task, the execution state of the task, and so on, and the worker thread dispatches the execution of the task through the interface. The following code implements the creation of a thread pool and the operation of removing threads from thread pools:

public class ThreadPool

{

Private Stack ThreadPool = new stack ();

private int poolsize;

private int currsize=0;

public void setSize (int n)

{

Poolsize = n;

}

public void Run ()

{

for (int i=0;i

The thread pool is suitable for applications

When the Web server accepts requests for a large number of short threads, it is appropriate to use the thread pooling technique, which can greatly reduce the number of threads created and destroyed, and increase the efficiency of the server. However, if the thread requires a longer run time and the thread runs much longer than the creation time, it is not obvious to improve the efficiency of the system by reducing the creation time, so it is not suitable for the application of thread pool technology, and other techniques are needed to improve the service efficiency of the server.

How to create a thread pool in Java

Related Article

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.