Discussion and application of Java threads (turn)

Source: Internet
Author: User
Tags abstract execution extend final garbage collection sleep thread thread class
Discussion and application of Java threads
Longs


One, why to study and use the thread
In general, the programs that the computer is executing are called processes (process), the processes have different address spaces, and are different programs running on the same system, such as W o r D and Excel , the communication between processes is time-consuming and limited. 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:

The use of multithreading parallel mechanism can solve many problems in interactive network programs, such as: a large number of network file resources read and write, user input response , animated display, and so on, do not require the number of times C P u, and time-consuming complex calculations usually do not require immediate response, so you do not need to give C p u all. For example, it may take 1 minutes to read a stream from a slow network, but it takes a very short time for the C P u to participate in the transmission of data; Respond to user input such as keystrokes , even the fastest input, 1 seconds keystrokes 1 0 times, also does not need C p U of how much time. Animation program is time-consuming, a painting in 1 seconds to redraw 5-1 0 times, but C P u in most of the time is still idle. 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 C P is idle for most of its time, it can only work in a step-by-minute manner. 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 grounding threads have the following characteristics (1) All the programs and data (2) of the thread sharing the parent process have its own runtime unit (3) has its own private storage and execution environment (especially the processor sends So that the server process does not increase linearly with the number of customers. Reduces server process pressure, lowers overhead, and leverages CPU resources. The above concurrent server at some point by the same server process generated by multiple concurrent threads to multiple clients concurrent requests to take the divide and conquer measures , which solves the problem of concurrent requests. 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 been scheduled yet. 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 these highest priority threads, once in a ready state, preempt the processor resources of the currently executing thread , the current thread can only find its place again in the waiting queue. 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 a higher priority thread object, it is best to let these threads discard the Control of the processor resources 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 to what the event is, it depends on the cause of the blockage: the thread in sleep must be blocked for a fixed period of time; A thread that is suspended or in a message waiting state must be awakened by a foreign event.

Dead
Dead indicates that 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 (the normal end), or that the thread was forced by another Interrupted (kill).

Iii. basic methods for creating and using threads
1. Generation of threads
In the Java language, there are two ways to generate a thread: one is to implement a runnable interface, and the other is to expand a thread class. Java.lang defines a pie directly from the root class object Raw thread class. All subclasses or indirect subclasses derived from this class are threads. In this way, a class that needs to be executed as a thread can only inherit and extend a single parent class. The following example expands the thread class to overwrite Thread.run () with its own implementation, resulting in a new class counter. The run () method is all the actions of the counter class thread.

Import java.lang.*;
public class Counter extends Thread
{
public void Run ()
{....}
}

The implementation of the Runnable interface is the most common method of generating threads, which breaks the limit of how to extend the thread class.
In the Java language source code, the Runnable interface contains only one abstract method, which is defined as follows:

Package java.lang.*;
Public interface Runnable {
public abstract void run ();
}

All objects that implement the Runnable interface can be executed as threads. The following example produces the same class as the example above. You can see that a thread class is used in the Counter class The variable.
Import java.lang.*;
public class counter implements Runnable
{Thread T;
public void Run ()
{...}
}
2. Basic methods
. public synchronized void Start ()

Starts the thread object, calls its run () method, and returns.

. Pubilc final void Stop ()

Stop the execution of the thread.

. Public final void Resume ()

Wakes a suspended thread. Valid only after the call to suspend ().

. Public final void Suspend ()

Suspends execution of a thread.

. public static void Yield ()

Temporarily aborts the running of the currently executing thread object. If there are other threads, then the next thread is called.

. public static void sleep (Long mills) throws Interruptedexception

Causes the currently running state of the thread to sleep mills milliseconds.

. Public final void Wait () throws Interruptedexception

Causes the thread to enter the wait state until it is awakened by another thread

. Public final void Motify ()

Notifies another waiting thread of the change in the state of the thread.

Four, the synchronization of the thread
The use of threads is primarily the work of multiple threads in a process, so thread synchronization is important. Thread synchronization is used for thread sharing data, transforming and controlling the execution of threads, and ensuring memory consistency.
In Java, run the Environment Use program (Monitor) to solve the problem of thread synchronization. Enhancement is a concurrency synchronization mechanism that includes data and methods for assigning a specific shared resource or a set of shared resources.

Java provides a unique enhancement for each object instance that has a synchronized method. In order to complete the function of allocating resources, the thread must call the pipe entry. The inlet of the pipe is the synchronized method. When the synchronization (synchronized) method is invoked, the thread obtains the pipe.

Strict mutual exclusion is imposed on the boundary of the pipe, at the same time, only one thread is allowed to enter the pipe path; When a thread is already in the pipeline, other threads that want to enter the pipe must wait, which is managed automatically by the pipe.

If the thread that calls the pipe entry discovers that the resource has been allocated, the thread in the pipe will invoke the wait action Waiting (). After entering wait (), the thread discards the pipe and waits outside the pipe so that other threads can enter the pipe.

Eventually, the resource-consuming thread calls a threaded entry to return the resource to the system, at which point the thread calls a notification operation notify (), notifying the system that one of the waiting lines is allowed The process obtains the process and obtains the resources. The threads that are notified are queued, thus avoiding infinite delay.

The Java.lang provides two ways to write a pipe: Notify () and wait (). There is also Notifyall (), which notifies all waiting threads to compete with the thread, and the result is that one gets the pipe and its di she returns to the waiting state.

Five, the control of the thread
The control of a thread is divided into a stop thread and a boot thread.
. Public final void Suspend ()

Suspends execution of a thread.

. Public final void Resume ()

Wakes a suspended thread. Makes a paused thread available for scheduling.

Because the scheduling of threads is a preemptive mechanism, threads can also be controlled using the priority of the thread.

. Public final void setpriority (int newpriority)

Sets the thread priority.

. public final int getpriority ()

Gets and returns the priority level of the thread.

The priority of the thread is used to sort the threads in the run queue, and the preemptive dispatch provided by Java enables the high-level thread to run first.

VI. Application of Threads
In practice, threads are used in a wide range of applications to control real-time data processing, fast network services, and faster image drawing and printing, and data in the database Retrieve and deal with and so on. In Java, an example of a non-stop operation that provides some basic services is the garbage collection thread, the garbage collection thread. This thread is provided by the Java Virtual machine. It scans the program for variables that are no longer being accessed, releasing the system resources it occupies into the system.



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.