In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the in-depth discussion on how to implement Java threads. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
1. What is a thread?
Generally speaking, we call a program being executed on a computer a "Process" rather than a process.
It is called a Program. The so-called "Thread" is the control flow of a single order in the "process".
Emerging operating systems, such as Mac,windows NT,Windows 95, mostly adopt the concept of multithreading.
The program is regarded as the basic execution unit. Threads are also an important part of Java.
Even the simplest Applet is done by multiple threads. In Java, any Applet
Both the paint () and update () methods are created by AWT (Abstract Window Toolkit) drawing and event handling lines.
The main milestone methods of Applet called by the program-- init (), start (), stop () and destory ()
Is called by the application that executes the Applet.
The concept of single threading is nothing new, but what is really interesting is the use of multiple lines in a program at the same time.
To accomplish different tasks. In some places, lightweight processes (Lightweig ht Process) are used instead of threads
The similarity between threads and real processes is that they are both single sequential control flows However, threads are considered lightweight.
Because it runs in the context of the whole program, it can use the resources and program environment shared by the whole program.
As a single sequential control flow, threads must have some resources as necessary overhead within the running program
. For example, there must be an execution stack and program counters. Code executed within a thread starts only in its context
Function, so in some places "execution context" is used instead of "thread".
two。 Thread attribute
In order to use threads correctly and effectively, it is necessary to understand all aspects of threads and Java real-time systems.
You must know how to provide thread bodies, thread lifecycles, how real-time systems schedule threads, thread groups,
What is a ghost thread (Demo nThread).
(1) Thread body
All operations occur in the thread body, which is the run () party that inherits from the Thread class in Java
Method, or the run () method in a class that implements the Runnable interface. When the thread is generated and initialized, the real-time system adjusts
Use its run () method. The code in the run () method implements the behavior of the generated thread, which is the main part of the thread
Points.
(2) Thread status
The attached figure shows the state that a thread can be at any time in its life cycle and causes a state change.
The way to change. This diagram is not a complete finite state diagram, but it basically summarizes the interest and popularity of threads.
In terms of. The thread life cycle is discussed below on this basis.
● New Thread State (New Thread)
A new thread is generated when a Thread object is generated. When a thread is in the "new thread" state, only the
An empty thread object that has not yet been assigned to system resources. So it can only be started or terminated. Any other fuck.
Doing will throw an exception.
● runnable state (Runnable)
The start () method generates the resources necessary to run the thread, schedules the thread's execution, and calls the thread's run
() method. At this point, the thread is runnable. This state is not called run state because the thread at this time is not
Always taking up the processor. Especially for PC with only one processor, there can only be one at any one time.
A runnable thread occupies the processor. Java realizes the sharing of processors by multi-thread through scheduling.
● non-operational state (Not Runnable)
When the following event occurs, the thread enters a non-running state.
The ① suspend () method is called
The ② sleep () method is called
The ③ thread uses wait () to wait for the condition variable
The ④ thread is waiting at Imax O.
● dead state (Dead)
When the run () method returns, or another thread calls the stop () method, the thread goes into a dead state. Usually Appl
Et uses its stop () method to terminate all threads it produces.
(3) Thread priority
Although we say that threads run concurrently. However, this is often not the case. As mentioned earlier, when
When there is only one cpu in the system, executing multithreading in a single CPU in some order is called scheduling (schedu
Ling). Java adopts a simple and fixed scheduling method, that is, fixed priority scheduling. This algorithm is
Scheduling is based on the relative priority of the runnable thread. When a thread is generated, it inherits the
Priority. The priority can be modified as needed. At any time, if there are multiple threads waiting to run
The system selects the runnable thread with the highest priority to run. Only when it stops, automatically gives up, or because of some kind of
Only threads with non-running and low priority can run. If two threads have the same priority, it
They will be run alternately.
The thread scheduling algorithm of Java real-time system is still mandatory, at any time, if one is better than the other lines
The state of the thread with high priority becomes runnable, and the real-time system will select the thread to run.
(4) Ghost thread
Any Java thread can become a ghost thread. It is used as an object running in the same process
And the thread's service provider. For example, HotJava browsers have a ghost called "background picture reader"
Thread, which reads pictures from the file system or network for objects and threads that need pictures.
Ghost threads are typical independent threads in applications. It provides for other objects and threads in the same application
Service. The run () method of ghost threads is typically an infinite loop, waiting for a service request.
(5) Thread group
Each Java thread is a member of a thread group. Thread groups provide a mechanism for multiple thread sets
Within an object, you can operate on them as a whole. For example, you can start or suspend with a method call
All threads in the group. The Java thread group is implemented by the ThreadGroup class.
When a thread is generated, you can specify a thread group or place it in a default thread group by the real-time system.
A thread can only belong to one thread group, and the thread group to which it belongs cannot be changed when the thread is generated.
3. Multithreaded program
I won't say much about the benefits of multithreading. But it also brings some new problems. as long as
Be very careful when designing the program, it is not too difficult to overcome these troubles.
(1) synchronize threads
Many threads must consider sharing data or coordinating execution state with other threads during execution. That's it.
A synchronization mechanism is required. In Java, each object has a lock corresponding to it. But Java does not provide a separate lo
Ck and unlock operations. It is implicitly implemented by the high-level structure to ensure the correspondence of the operation. (however, we note that
It is intended that the Java virtual machine provides separate monito renter and monitorexit instructions to implement lock and unlo
Ck operation.)
The synchronized statement calculates an object reference, attempts to lock the object, and completes the
Stop processing before locking operation. When the lock operation is completed, the synchronized statement body is executed. When the sentence aspect executes
After completion (whether normal or abnormal), the unlock operation is completed automatically. As an object-oriented language, synchronized
Often used with methods. A better way is if a variable is assigned by one thread and by another line
Program reference or assignment, then all access to the variable must be in a synchromized statement or synch
Within the ronized method.
Now suppose a situation in which both thread 1 and thread 2 have to access a data area and require access from thread 1
If you ask before thread 2, then using synchronized alone will not solve the problem at this time. This is in unix or Windows
Simaphore can be used in NT. Java does not provide. Wait () and noti are provided in Java
Fy () mechanism. The use is as follows:
Synchronized method-1 (…) {call by thread 1.
∥ access data area
Available=true
Notify ()
}
Synchronized method-2 (…) {∥ call by thread 2.
While (! available)
Try {
Wait (); ∥ wait for notify ().
} catch (Interrupted Exception e) {
}
∥ access data area
}
Where available is a class member variable and the initial value is set to false.
If you check that available is false in method-2, wait () is called. The function of wait () is to make the line
Program 2 enters the non-running state and unlocks it. In this case, method-1 can be called by thread 1. When executed
After notify (). Thread 2 changes from a non-running state to a runnable state. When the method-1 call returns. Thread 2
The object can be re-locked, and the instruction returned by wait () can be executed after the lock is successful. This mechanism can also be applied to
Other more complicated situations.
(2) deadlock
If there are several concurrent threads competing for resources in the program, it is important to ensure balance. System equilibrium
Means that each thread has full access to limited resources during execution. There are no starvation or deadlocks in the system.
Thread. Java does not provide a deadlock detection mechanism. For most Java programmers, preventing deadlocks is
A better choice. The easiest way to prevent deadlocks is to introduce sequence numbers to competing resources, if a line
A program needs several resources, so it must first get a resource with a small sequence number, and then apply for a resource with a large sequence number.
This is the end of the in-depth discussion on how to implement Java threads. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.
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.