In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Xiaobian to share with you what Java thread is used, I believe most people do not know how, so share this article for everyone's reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
Why study and use threads
Generally speaking, the programs being executed by a computer are called processes, processes have different address spaces and are different programs running on the same system, such as Word and Excel, and 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 pipes, message queues, shared memory, or signal processing to ensure interprocess communication. Although many programs are running, you can only deal with one program at a time.
A thread is a single sequential flow of control within a process. Also known as lightweight processes. Threads share the same address space and together form one large process. Inter-thread communication is very simple and efficient, context switching is very fast and part of the overall program switching. Threads are just procedure calls that execute independently of each other, and threads make programming more free and rich within an application. Threads are interested in using multiple threads simultaneously to accomplish different tasks in a program. Threads, if well utilized, can greatly simplify application design. Multithreading improves program interactivity, providing better capabilities and functionality, better GUIs, and better server functionality. Two examples are given below:
Example 1: Using multi-thread parallel mechanism can solve many problems in interactive network programs well, such as: reading and writing a large number of network file resources, user input response, animation display and other problems do not require much CPU time; time-consuming complex calculations usually do not require immediate response, so there is no need to give it all CPU. For example, it may take a minute to read a data stream from a slow network, but the time required for the CPU to participate in transmitting the data is very short; responding to user input such as keystrokes, even the fastest typist, 10 keystrokes per second, does not require much CPU time. Animation programs are time-consuming, with a painting redrawn 5-10 times in a second, but the CPU remains idle most of the time. The problem with traditional single-threaded environments is that users must wait for each task to complete before moving on to the next. Even if the CPU is idle most of the time, it can only work step by step. Multithreading can solve these problems well without causing users to wait. For example, time-consuming complex computing applications can be divided into two control threads: one for handling user events in the GUI and the other for background computing.
Example 2: For example, concurrent servers, which are oriented to requests processed in an indefinite period of time, are processed by threads of the server for each request. Traditional concurrent servers are often based on multi-process mechanism, each client has a process, which needs the intervention of operating system, and the number of processes is limited by operating system. This paper uses Java thread mechanism to build concurrent server based on multithread. Generating and managing them is a fairly simple operation. Threads are used to build request-driven service programs, one thread per client, and multiple threads can execute concurrently. In particular, a thread has the following characteristics: (1) it shares all programs and data of the parent process;(2) it has its own execution unit; and (3) it has its own private storage and execution environment (especially processor registers), so that the server process does not increase linearly with the number of clients. It can reduce the pressure on the server process, reduce overhead, and make full use of CPU resources. The above concurrent server takes measures to divide and rule concurrent requests of multiple clients by multiple concurrent threads generated by the same server process at a certain moment, thus solving the problem of concurrent requests. Each thread can operate independently or collaboratively. Reduce the complexity of the server.
Java is designed on top of an operating system-level multithreaded environment, Java's runtime relies on multithreading to execute tasks, and all class libraries are designed with multithreading in mind.
Structure of Java Thread
Java supports a "preemptive" scheduling approach.
Thread from generation to disappearance, can be divided into 5 states:
Newborn
A thread is in a special "Newborn" state during the time it has been created but not executed, when the thread object has been allocated memory space, its private data has been initialized, but the thread has not yet been dispatched. Thread objects can be dispatched by the start () method, or killed by the stop () method. The newly created thread switches to the "Runnable" state as soon as it is scheduled.
Runnable
Runnable means the ready state of a thread, indicating that the thread is waiting for processor resources to be invoked for execution at any time. Threads that are in a ready state are actually scheduled, that is, they have been placed in a queue waiting to be executed. When a thread in a ready state can actually execute depends on the thread priority and the current state of the queue. Threads with the same priority follow a "first come, first served" scheduling principle.
The thread enters the corresponding position of the waiting queue according to its own priority. Some system threads have the highest priority, and once these highest priority threads enter the ready state, they will preempt the processor resources of the currently executing thread, and the current thread can only find its own place in the waiting queue again. After these highest priority threads finish their tasks, they sleep for a while, waiting to be awakened by an event. Once called, these threads start grabbing processor resources again. These highest-priority threads are usually used to perform critical tasks, such as on-screen display.
Low-priority threads wait longer to get a chance to run. Since the system itself cannot abort high-priority threads, if you use higher-priority thread objects in your program, it is best to let those threads give up control of processor resources from time to time so that other threads can run organically.
Running
The "Running" state indicates that the thread is running, that the thread has taken control of the processor, and that its code is currently running. This thread will run until it is finished, unless control of the running process is taken over by a higher priority thread.
In summary, threads release control of the processor in three situations:
1. Active or passive release of control over processor resources. At this point, the thread must enter the wait queue again, waiting for other threads of higher or equal priority to finish executing.
2. Sleep for a certain period of time without entering the waiting queue. After the expiration of this defined time period, the operation is restarted.
3. Waiting for an event to wake you up.
Blocked
If a thread is in a "blocked" state, then temporarily the thread will not be able to enter the ready queue. A thread that is stuck usually has to be awakened by some event. The event depends on the cause of the congestion: a sleeping thread must be blocked for a fixed period of time; a suspended or waiting thread must be awakened by an external event.
Dead
Dead indicates that the thread has exited the running state and is no longer in the ready queue. The reason may be that the thread has finished executing (normal end), or it may be that the thread is forcibly interrupted by another thread (kill).
Basic methods of creating and using threads
1. thread generation
In Java, there are two ways to generate threads: one is to implement a Runnable interface, and the other is to extend a Thread class.java.lang defines a Thread class that derives directly from the root class Object. All subclasses or indirect subclasses derived from this class are threads. In this way, a class that needs to execute as a thread can only inherit and extend a single parent class. The following example generates a new class Counter by extending the Thread class and overriding Thread.run() with the thread's own implementation. The run() method is all that the Counter class thread does.
import java.lang.*; public class Counter extends Thread { public void run () {....} }
Implementing a Runnable interface is the most common way to generate threads, breaking the limits of the Thread class approach.
In Java, the Runnable interface contains only one abstract method, defined as follows:
package java.lang.*; public interface Runnable { public abstract void run (); }
All objects that implement the Runnable interface can be executed threadably. The following example produces the same class as the above example. You 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 return.
.pubilc final void stop()
Stops thread execution.
.public final void resume()
Wake up suspended threads. Valid only after suspension () is called.
.public final void suspend()
Suspends thread execution.
.public static void yield()
Temporarily suspends the execution of a thread object that is currently executing. If there are other threads, then the next thread is invoked.
.public static void sleep(longmills)throws Inter rupted Exception
Sleeps the currently running thread for milliseconds.
.public final void wait()throws Interrupted Exception
Put a thread into a waiting state until awakened by another thread
.public final void motify()
Notify another waiting thread of the change in thread state.
IV. Synchronization of threads
The use of threads mainly lies in the collaborative work of multiple threads in a process, so synchronization of threads is very important. Thread synchronization is used for threads to share data, convert and control thread execution, and ensure memory consistency.
In Java, the runtime environment uses a program (Monitor) to solve the problem of thread synchronization. A pipe is a concurrent synchronization mechanism that includes data and methods for allocating a particular shared resource or set of shared resources.
Java provides a unique pipe for each instance of an object that has synchronized methods. In order to complete the function of allocating resources, a thread must call a pipe entry. A pipe entry is a synchronized method entry. When the synchronized method is called, the thread gets the pipe.
A strict mutual exclusion is enforced on the pipe boundary, and only one thread is allowed to enter the pipe at a time; when there is already one thread in the pipe, other threads wishing to enter the pipe must wait, which is automatically managed by the pipe.
If the thread calling the pipe entry finds that the resource has been allocated, the thread in the pipe calls the wait() operation. After entering wait(), the thread relinquishes possession of the pipe and waits outside the pipe for other threads to enter the pipe.
Finally, the thread that owns the resource will call an entry of a pipe to return the resource to the system, in which case it needs to call a notify() operation to notify the system to allow one of the waiting threads to acquire the pipe and get the resource. Notified threads are queued, thus avoiding infinite procrastination.
Java.lang provides two methods for programming:notify() and wait(). There is also notifyAll(), which notifies all waiting threads to compete for the pipe, resulting in one of them getting the pipe and the other returning to the waiting state.
V. Control of threads
Thread control is divided into stopping threads and starting threads.
.publicfinalvoidsuspend()
Suspends thread execution.
.publicfinalvoidresume()
Wake up suspended threads. Make a suspended thread available for scheduling.
Because thread scheduling is preemptive, thread priorities can also be used to control threads.
.publicfinalvoidsetPriority(intnewPriority)
Set thread priority.
.publicfinalintgetPriority()
Gets and returns the priority of the thread.
Thread priority is used to order threads in the run queue, Java provides preemptive scheduling so that higher-level threads run first.
VI. Application of Thread
In practice, threads are used in a wide range of applications, such as controlling real-time data processing, fast network services, faster image rendering and printing, and retrieving and processing data from databases. An example of a non-stop running service in Java that provides some basic services is the garbage collection thread. This thread is provided by the Java Virtual Machine. It scans the program for variables that are no longer accessed and releases system resources to the system.
The above is "Java thread what to use" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.