Create a thread pool in Java

Source: Internet
Author: User
A thread is a major feature of Java. It can be a given sequence of commands, variables defined in a given method, or shared data (Class-level variables ). In Java, each thread has its own stack and program.
Counter (PC), where the stack is used to trace the context of the thread (context is the value of the current local variable when the thread is executed somewhere ), the program counter is used to track the commands being executed by the current thread.

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

1. queuing status
(Ready), this thread does not run immediately after the user creates a thread. When the method start () in the thread is called, the thread will queue and wait for the scheduler to send it
Transfer to running status (running ). After a process is executed, it can also be queued. If the scheduler permits this, you can call the yield () method to put the process in a queue.
Status.

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

3. The waiting state (waiting) may cause the thread to be in the waiting state for many reasons, such as being paused during thread execution or waiting for the completion of the I/O request to enter the waiting state.

In
Different threads in Java have different priorities. High-priority threads can be completed before low-priority threads. If multiple threads have the same priority, Java switches between different threads.
Run. An application can set the priority of a thread by using the method setpriority () in the thread. The method getpriority () is used to obtain the priority of a thread.
Level.

Thread Lifecycle

The life cycle of a thread can be divided into two stages: The Life Cycle (alive) and the death cycle.
(Dead), in which the life cycle also includes running and waiting ). After a new thread is created, the thread enters the queue state.
(Ready), when the method start () in the thread is called, the thread enters the Life Cycle. At this time, its method isalive () always returns the true value until the thread enters the dead state.

Thread implementation

There are two ways to implement the thread, one is to extend the java. Lang. Thread class, and the other is through the java. Lang. runnable interface.

Thread
Class encapsulates the thread behavior. To create a thread, you must create a new class extended from the Thread class. Because the method run () in the Thread class does not provide any operations
When creating a thread, you must overwrite the run () method to complete useful work. When the START () method in the thread is called, The run () method is called again. The following code is extended
Thread class to implement the thread:

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 );
}

Connect
When you want a class to run in your own thread and expand the features of some other classes, you need to run the runnable interface. The runnable interface has only one method.
Run (). Whenever a class using the runnable interface is created, you must write the run () method in the class to overwrite the run () method in the interface. For example, the following code is
Threads 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-r <I | Y + r> getsize (). Height)
Y1 * =-1;
Try {
T. Sleep (sleeptime );
} Catch (interruptedexception e ){}
}
}
}

Why use thread pool?

In
In Java, if a new thread is created every time a request arrives, the overhead is considerable. In actual use, the time and consumed by the server for each request to create a new thread During the creation and destruction of the thread
Unified resources may even be much longer than the time and resources spent processing actual user requests. In addition to the overhead of creating and destroying threads, active threads also consume system resources. If you create
Too many threads may cause system resources to be insufficient due to excessive memory consumption or excessive switching. To prevent resource insufficiency, server applications need some measures to limit the processing at any given time point.
The number of requests to minimize the number of threads created and destroyed, especially the creation and destruction of some threads with high resource consumption, and try to use existing objects for service, this is the result of "pooled resources" technology.
Cause.

The thread pool is mainly used to solve the thread lifecycle overhead and resource insufficiency issues. By reusing threads for multiple tasks, the thread-created overhead is apportioned to multiple tasks,
In addition, because the thread already exists when the request arrives, the delay caused by thread creation is eliminated. In this way, the application can immediately respond to the request. In addition, adjust
The number of threads can prevent resource insufficiency.

Create a thread pool

A relatively simple thread pool should contain at least thread pool management
Task, worker threads, task queues, task interfaces, and so on. The thread pool manager (threadpool
Manager) is used to create, destroy, and manage the thread pool, and put the worker thread into the thread pool. The worker thread is a thread that can execute tasks cyclically and waits when no task exists; task queue
A buffer mechanism is provided to put unprocessed tasks in the task queue. The task interface is an interface that must be implemented by each task, it is mainly used to specify the task entry, the finishing work after the task is executed, and the task execution
The job thread schedules the execution of tasks through this interface. The following code creates a thread pool and extracts 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 <poolsize; I ++)
{
Workthread = new workthread ();
Threadpool. Push (workthread );
Currsize ++;
}
}
Public synchronized workthread getworker ()
{
If (threadpool. Empty ())
System. Out. println ("stack is empty ");
Else
Try {return threadpool. Pop ();
} Catch (emptystackexception e ){}
}
}

The thread pool is suitable for applications.

When
When a web server receives a large number of requests from short threads, It is very suitable to use the thread pool technology. It can greatly reduce the number of thread creation and destruction times and improve the efficiency of the server. However, if the thread requires
The thread running time is longer. At this time, the thread running time is much longer than the creation time. Reducing the creation time alone does not significantly improve the system efficiency. In this case, the thread pool technology is not suitable for application, other technologies are needed
Improve the service efficiency of the server.
From-ccidnet

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.