Discussion and application of Java threads

Source: Internet
Author: User

One, why to study and use the thread

Generally speaking, the programs that the computer is executing are called processes (process), the processes have different address spaces, and different programs that run on the same system, such as Word and Excel, are time-consuming and limited in-process communication. Context switching, changing the running process is also very complex. interprocess communication is complex and may require pipeline, Message Queuing, shared memory (sharedmemory), or signal processing to ensure interprocess communication. Although many programs are running, you can only deal with one program at a time.

Thread is a single sequential flow of control in a process. Also known as lightweight processes. Threads share the same address space and collectively constitute a large process. Communication between threads is very simple and effective, context switching is very fast and is a part of the entire large program switch. Threads are only procedure calls, which execute independently of each other, and threads make programming more free and rich in one application. The interest of threads is that multiple threads are used in one program to accomplish different tasks. So if you make good use of threads, you can greatly simplify your application design. Multithreading improves program interactivity, providing better capabilities and functionality, better GUI, and better server functionality. Give two examples to illustrate the following:

Using multithread parallel mechanism can solve many problems in the interactive network program well, such as: a large number of network file resources to read and write, user input response, animation display and other issues do not require the amount of time the CPU, and time-consuming complex calculation usually does not require immediate response, so do not need to give the CPU all to it. For example, it may take 1 minutes to read a stream from a slow network, but it takes a very short time for the CPU to be involved in the transfer of data; In response to user input such as keystrokes, even the fastest input, 1 seconds keystrokes 10 times, also does not need the CPU how much time. Animation program is time-consuming, a painting in 1 seconds to redraw 5-10 times, but the CPU is still idle for most of the time. The problem with the traditional single-threaded environment is that users must wait for each task to complete before they can perform the next task. Even if the CPU is idle for most of the time, it can only work step-by-minute. Multithreading can be a good solution to these problems to avoid causing users to wait. Such as: Time-consuming complex computing applications can be divided into two control threads: a user event to handle the GUI, and the other for background computing.

Example two: A concurrent server, which faces requests that are processed for an indefinite length of time, is handled by the server's thread for each request. Traditional concurrent servers are often based on multiple process mechanisms, each client a process that requires the intervention of the operating system, the number of processes is limited by the operating system. This paper uses Java thread mechanism to build a concurrent server based on multithreading. Building and managing them is a fairly simple operation. Threads are used to create a request-driven service program, one thread per client, and multiple threads can execute concurrently. Special ground threads have the following characteristics (1) All Programs and data (2) of thread-sharing parent processes have their own operating units (3) have their own private storage and execution environment (especially processor registers), which makes the server process not linearly increase with the number of customers. Reduces server process pressure, lowers overhead, and leverages CPU resources. The above concurrent server solves the problem of concurrent requests by dividing and dividing the concurrent requests of multiple clients at some instant by multiple concurrent threads generated by the same server process. Each thread can operate independently, and it can work together. Reduces the complexity of the server.

Java is designed on the basis of an operating system-level multithreaded environment, and the Java runtime relies on multithreading to perform tasks, and all class libraries are designed with multithreaded mechanisms in mind.

Second, the structure of Java threads

Java supports a "preemptive" (preemptive) scheduling approach.

Threads can be divided into 5 states from generation to extinction:

Newborn

The thread is in a special "newborn" state when it has been created but not executed, at which point the thread object has been allocated memory space and its private data has been initialized, but the thread has not yet been dispatched. The thread object can be scheduled by the start () method or killed by the Stop () method. Once the newly created thread is dispatched, it switches to the "Runnable" state.

Runnable

Runnable is the ready state of the thread, indicating that the thread is waiting for the processor resource to be invoked at any time. Threads in a ready state are actually scheduled, that is, they have been placed in a queue for execution. When a thread in the ready state can be truly executed, depends on the thread priority and the current status of the queue. If the thread has the same priority, it will follow the "first come first served" scheduling principle.

The thread enters the corresponding position of the wait queue according to its own priority. Some system threads have the highest priority, and once they are in a ready state, the processor resources of the currently executing thread are preempted, and the current thread can only reconnect to the waiting queue for its own location. These top-priority threads will sleep for a period of time after performing their own tasks, Waiting to be awakened by an event. Once called, these threads start to preempt the processor resources. These highest priority threads are typically used to perform some critical tasks, such as on-screen display.

A low priority thread waits longer to have a chance to run. Because the system itself cannot abort the execution of high-priority threads, if your program uses higher-priority thread objects, it is best to let these threads discard control of the processor resources from time to time so that other threads can run organically.

Running

The "Running" (running) state indicates that the thread is running, that the line has control over the processor, and that the code is currently running. This thread will run until it is finished, unless the control of the running process is taken over by a higher priority thread.

In combination, threads will release control of the processor in the following 3 scenarios:

1. Actively or passively release control over the processor resources. At this point, the thread must enter the wait queue again, waiting for other high priority or equal threads to finish executing.

2. Sleep a certain period of time, do not enter the waiting queue. After the time period that is determined expires, start running again.

3. Waiting for an event to awaken itself.

Blocked

If a thread is in a "Blocked" state, then the thread will not be able to enter the ready queue temporarily. A thread in a blocked state usually must be awakened by some event. As for what happens, it depends on the cause of the blockage: a thread in sleep must be blocked for a fixed amount of time; a thread that is suspended or in a message waiting state must be awakened by a foreign event.

Dead

Dead the line Cheng out of the running state and is no longer in the ready queue. The reason may be that the line Cheng finished (normal), or that the thread was forcibly interrupted (kill) by another process.

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.