Java basics-Creating a thread pool in a Java program

Source: Internet
Author: User
Tags execution implement interface resource sleep variable thread thread class
Programs | creating

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

In general, one thread cannot access another thread's stack variable, and the thread must be in one of the following states:

1. Queued status (Ready), which does not run immediately after the user creates a thread. When the method start () in the thread is invoked, the thread queues 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 placed in a queued state by invoking method yield ().

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

3. The wait state (waiting) can cause a thread to be in a waiting state, such as being paused during thread execution, or waiting for an I/O request to complete.

Different threads in Java have different priorities, and high-priority threads can be scheduled to complete before the 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.

Life cycle of threads

The life cycle of a thread 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 when the method start () is invoked in the thread, the thread enters the life cycle, and its method IsAlive () always returns the true value until the thread enters the dead state.

Implementation of Threads

There are two ways to implement threads, one is to extend the Java.lang.Thread class, and the other is through the Java.lang.Runnable interface.

The thread class encapsulates the behavior of threads. To create a thread, you must create a new class that extends from the thread class. Because method run () does not provide any action in the thread class, the user must overwrite method run () to do useful work when the thread is created. Method Run () is invoked when the method start () in the thread is called. The following code is to implement 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);
}

Typically, when a user wants a class to run on its own thread and also extends the attributes of some other classes, it needs to be implemented with the help of 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 the thread that is 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 to use the thread pool

In Java, if you create a new thread every time a request arrives, the overhead is quite large. In practice, each server that requests the creation of a new thread spends more time and consumes more system resources on creating and destroying threads than on the actual user requests. In addition to the overhead of creating and destroying threads, the active thread also consumes system resources. Creating too many threads in one JVM can cause system resources to be low due to excessive memory consumption or "switching over". In order to prevent the lack of resources, server applications need some way to limit the number of requests processed at any given time, minimizing the number of threads created and destroyed, especially the creation and destruction of some of the more expensive threads, as far as possible using existing objects for service, which is why "pooled resources" technology arises.

Thread pooling is primarily used to resolve thread lifecycle overhead issues and resource shortages. By reusing threads for multiple tasks, the cost of thread creation is spread across multiple tasks, and the delay caused by thread creation is eliminated because the thread already exists when the request arrives. This allows the request to be serviced immediately so that the application responds faster. In addition, you can prevent resource shortages by appropriately adjusting the number of threads in the thread pool.

Create a thread pool

A simpler thread pool should contain at least the thread pool manager, worker thread, Task queue, task interface, and so on. Where the thread pool manager (ThreadPool Manager) creates, destroys, and manages the thread pool, putting worker threads into the thread pool; A worker thread is a thread that can loop through a task and wait when there is no task; the role of a task queue is to provide a buffer mechanism, Put the unhandled tasks in the task queue; The task interface is the interface that each task must implement, which is mainly used to specify the portal of the task, the finishing work after the task is performed, the execution status of the task, and so on, the worker thread schedules the task execution through the interface. The following code implements the operation of creating a thread pool and removing threads from the thread pool:

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

thread pool suitable for application occasions

When a Web server accepts requests for a large number of short threads, it is appropriate to use thread pooling technology, which can greatly reduce the number of threads created and destroyed and improve server productivity. However, if the thread requires a longer run time, the thread is running longer than the creation time, the reduction of creation time on the system efficiency is not obvious, at this time is not suitable for the application of thread pooling technology, the need to use other technologies to improve server service efficiency.



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.