Discussion and Application of Java threads

Source: Internet
Author: User
Java thread discussion and application-Linux general technology-Linux programming and kernel information. The following is a detailed description. I. Why study and use threads?
Generally, a program that is being executed by a computer is called a process. A process has different address spaces and runs different programs on the same system, such as WORD and Excel, inter-process communication is very time-consuming and limited. Context switching and changing processes are also very complicated. Inter-process communication is complex and may require pipelines, message queues, shared memory (sharedmemory), or signal processing to ensure inter-process communication. Although many programs are running, they can only deal with one program at a time.
A thread is a single-Order Control Flow in a process. It is also called a lightweight process. The thread shares the same address space and forms a large process together. Inter-thread communication is very simple and effective. Context switching is fast and part of the entire large program. Threads are only process calls, and they are executed independently of each other. The thread makes programming in an application more free and rich. The thread is interested in using multiple threads in a program to complete different tasks at the same time. Therefore, using threads can greatly simplify application design. Multithreading can enhance the interaction of programs, provide better capabilities and functions, better GUI and better server functions. Here are two examples:

Example 1: multi-thread parallel mechanism can be used to solve many problems in interactive network programs, such: A large number of network file resources, such as reading and writing, user input response, and animation display, do not require much CPU time. However, complex computing that consumes time usually does not need to respond immediately, so you don't need to give it all the CPU. For example, it may take one minute to read a data stream from a slow network, but the time required for the CPU to participate in data transmission is very short. Responding to user input, such as a key, even if the fastest Inspector presses the key 10 times in one second, it does not need much CPU time. The animation program is time-consuming. A picture must be repainted 5-10 times in 1 second, but the CPU is still idle for most of the time. In the traditional single-threaded environment, you must wait for each task to complete before proceeding to the next task. Even if the CPU is idle most of the time, it can only work in a step-by-step manner. Multithreading can effectively solve these problems to avoid user waiting. For example, a time-consuming complex computing application can be divided into two control threads: one for processing GUI user events and the other for background computing.

Example 2: For a concurrent server, it is oriented to requests that have been processed in an indefinite period of time, and each request is processed by the server thread. Traditional concurrent servers are often based on multi-process mechanisms. Each customer has a single process and requires the intervention of the operating system. The number of processes is limited by the operating system. This article uses the Java thread mechanism to establish a multi-thread-Based Concurrent Server. Generating and managing them is quite simple. A thread is used to establish a request-driven service program. Each client has one thread and multiple threads can be concurrently executed. Special threads have the following features: (1) threads share all programs and data of the parent process (2) have their own running units (3) it has its own private storage and execution environment (especially processor registers), so that server processes do not linearly increase with the increase in the number of customers. Reduces the pressure on server processes, reduces overhead, and makes full use of CPU resources. The preceding concurrent server uses the multiple concurrent threads generated by the same server process to divide and conquer the concurrent requests of multiple clients at a certain moment, thus solving the problem of concurrent requests. Each thread can operate independently and collaborate with jobs. Reduces server complexity.

Java is designed based on the operating system-level multi-threaded environment. Java runners rely on multithreading to execute tasks, and all class libraries are designed with the multithreading mechanism taken into account.

Ii. Java thread structure
Java supports preemptive scheduling.
The thread can be in five states from generation to Elimination:
The thread is in a special "Newborn" State during the period when it has been created but not executed. At this time, the thread object has been allocated memory space and its private data has been initialized, however, this thread has not been scheduled. In this case, the thread object can be scheduled using the start () method, or the stop () method is used to kill the thread. Once a newly created thread is scheduled, it will switch to the "Runnable" state.

Runnable indicates the ready state of the thread, indicating that the thread is waiting for the processor resources and can be called and executed at any time. In fact, the ready threads have been scheduled, that is, they have been placed in a queue for execution. When a ready thread can be actually executed depends on the thread priority and the current status of the queue. If the thread has the same priority, it will follow the Scheduling Principle of "first come first service.

The thread enters the corresponding position of the waiting queue based on its priority. Some system threads have the highest priority. Once these threads are ready, they will seize the processor resources of the currently executing threads. The current thread can only wait for the queue to find its position. after the threads with the highest priority finish their tasks, they will sleep for a period of time and wait for a certain event to wake up. once called, these threads start to seize processor resources. These top-priority threads are generally used to execute some key tasks, such as on-screen display.

Low-priority threads need to wait for a longer time before they can run properly. Because the system itself cannot stop the execution of high-priority threads, if your program uses a thread object with a higher priority, it is recommended that these threads give up control of the processor resources from time to time, to allow other threads to run organically.

"Running" indicates that the thread is Running and the thread has control over the processor. Its code is currently Running. This thread will run until it is finished, unless the control of the running process is heavily occupied by a higher-priority thread.

In combination, the thread will release control of the processor in the following three cases:

1. actively or passively release control of processor resources. At this time, the thread must enter the waiting queue again and wait for other threads with high priority or equal level to complete execution.

2. sleep for a certain period of time and do not enter the waiting queue. After the specified period expires, run the task again.

3. Wait for an event to wake up.

If a thread is in the "Blocked" status, the thread cannot enter the ready queue temporarily. A thread in the congested state must be awakened by some events. The event depends on the cause of the congestion: the thread in the sleep must be blocked for a fixed period of time; A suspended thread or a thread in the message waiting state must be awakened by an external event.

Dead indicates that the thread has exited the running status and no longer enters the ready queue. the reason may be that the thread has been executed successfully (normally ended), or that the thread has been forcibly interrupted by another thread (kill ).

3. Basic methods for creating and using threads
1. Thread generation
In Java, two methods can be used to generate threads: one is to implement a Runnable interface, and the other is to expand a Thread class. java. lang defines a Thread class derived directly from the root class Object. all subclasses or indirect subclasses derived from this class are threads. In this way, the class to be executed as a thread can only inherit and expand a single parent class. The following example expands the Thread class and overwrites Thread. run () with the implementation of this Thread to generate a new Counter class. The run () method is all operations performed by Counter threads.
Import java. lang. *; public class Counter extends Thread {public void run (){....}}

Implementing the Runnable interface is the most common Thread generation method, which breaks the restrictions on extending the Thread class.
In the Java source code, the Runnable interface only contains an abstract method, which is defined as follows:
Package java. lang. *; public interface Runnable {public abstract void run ();}

All the objects of classes that implement the Runnable interface can be executed in the Thread mode. The following example generates the same class as the above example. We can see that the counter class uses a variable of the Thread class.
Import java. lang .*;
Public class counter implements Runnable {Thread T; public void run (){...}}
2. Basic Methods
. Public synchronized void start ()

Start the thread object, call its run () method, and then return.

. Pubilc final void stop ()

Stop thread execution.

. Public final void resume ()

Wake up the suspended thread. Valid only after suspend () is called.

. Public final void suspend ()

Suspends the execution of a thread.

. Public static void yield ()

Temporarily stop the running of the currently executing thread object. If other threads exist, the next thread is called.

. Public static void sleep (longmills) throws Inter rupted Exception

Sleep the thread in the current running state in milliseconds.

. Public final void wait () throws Interrupted Exception

Wait until the thread is awakened by another thread.

. Public final void motify ()

Notifies another waiting thread of changes in the thread status.

4. Thread Synchronization
The use of threads is mainly because multiple threads in a process work collaboratively, so thread synchronization is very important. Thread Synchronization is used to share data, convert and control thread execution, and ensure memory consistency.
In Java, the running environment uses the program (Monitor) to solve the thread synchronization problem. A concurrency synchronization mechanism includes data and methods used to allocate a specific shared resource or a group of shared resources.

Java provides a unique process for every object instance with the synchronized method. To complete the resource allocation function, the thread must call the management entry. The pipe process entry is the synchronized Method entry. When the synchronous (synchronized) method is called, the thread obtains the thread.

Strict mutual exclusion is implemented on the pipe process boundary. At the same time, only one thread is allowed to enter the pipe process. When a thread already exists in the pipe process, other threads wishing to enter the pipe process must wait, this kind of wait is automatically managed by the manager.

If the thread that calls the connection entry finds that the resource has been allocated, the thread in the connection will call wait () to wait for the operation (). After entering wait (), the thread stops occupying the management thread and waits outside the management thread so that other threads can enter the management thread.

In the end, the resource-consuming thread will call a pipe program entry to return the resource to the system. At this time, the thread needs to call a notification operation notify (), the notification system allows one of the waiting threads to obtain the pipeline and obtain resources. The notified thread is queued to avoid infinite delay.

In Java. lang, two methods are provided for writing a pipe program: notify () and wait (). In addition, yyall () is used to notify all the waiting threads so that they can compete for the pipeline. The result is that one of them obtains the pipeline and Its scheduler returns the waiting state.

5. thread control
Thread control is divided into stop thread and start thread.
. Publicfinalvoidsuspend ()

Suspends the execution of a thread.

. Publicfinalvoidresume ()

Wake up the suspended thread. Enables a paused thread to be used for scheduling.

Because thread scheduling is a preemptible mechanism, you can also use the thread priority to control the thread.

. PublicfinalvoidsetPriority (intnewPriority)

Set the thread priority.

. PublicfinalintgetPriority ()

Obtains and returns the priority of a thread.

The thread priority is used to sort threads in the running queue. The preemptible scheduling provided by Java enables advanced threads to run first.

Vi. Application of threads
In practical applications, threads are widely used to control real-time data processing, fast network services, faster Image Rendering and printing, and data retrieval and processing in databases. In Java, an example of providing some basic services is the garbage collection thread and garbage collection thread ,. This thread is provided by the Java Virtual Machine. It scans variables that are no longer accessed in the program and releases the system resources it occupies to the system.
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.