In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what is the multithreaded programming method for implementing Runnable interface. The content of the article is of high quality. Therefore, Xiaobian shares it with you as a reference. I hope that after reading this article, you will have a certain understanding of relevant knowledge.
A Multithreaded Programming Method for Implementing Runnable Interface
Another way to implement multithreaded applications provided in the Java language is for multithreaded objects to implement the Runnable interface and define a run method in the class for starting threads. The advantage of this definition is that multithreaded application objects can inherit other objects rather than having to inherit Thread classes, thereby increasing the logic of class definitions.
The multithreaded application framework code implementing the Runnable interface looks like this:
//Consumer.java
import java.util.*;
class Consumer implements Runnable
{
… …
public Consumer(int nTime, String strConsumer){… …}
public void run(){… …}
static public void main(String args[])
{
Thread aConsumer = new Thread(new Consumer(1000, "aConsumer"));
aConsumer.start();
//Running threads of other object instances
//… …
}
}
As you can see from the above code, this class implements the Runnable interface and defines the run method in this class. An important difference between the implementation of this multithreaded application and multithreaded applications that inherit the Thread class is the design of the methods used to launch multithreaded objects. In the above code, by creating an instance of Thread object and applying the object as an argument to create an instance of Thread class.
synchronization between threads
Multiple threads of a Java application share data resources of the same process, and multiple user threads may access sensitive content simultaneously during concurrent execution. Java defines the concept of thread synchronization to achieve consistency maintenance of shared resources. Following is a description of the implementation of multi-thread synchronization in Java language by using the method of synchronization control between threads in mobile communication billing system recently developed by the author.
The customer account class definition framework code without the multithreaded synchronization control policy is as follows:
public class RegisterAccount
{
float fBalance;
//Customer Payment Method
public void deposit(float fFees){ fBalance += fFees; }
//Call billing method
public void withdraw(float fFees){ fBalance -= fFees; }
… …
}
The reader may think that the above program code is sufficient to meet the actual needs of the billing system. Indeed, the program is reliable in a single-threaded environment. But what happens when multiple processes run concurrently? Suppose that the customer is making a payment at the customer service center while using the mobile communication device to make a call, and the billing system initiates the billing process at the end of the customer call, while the service center staff also submits the payment process to run. Readers can see that if this happens, the handling of customer accounts is not serious.
How to solve this problem? Simply add the keyword synchronized to the RegisterAccount class method definition to identify the synchronized method. In this way, shared resources involved in a synchronous method during its execution (in the code above, the fBalance member variable) are locked to ensure that only the method can access the shared resources during the execution of the method, and that no other thread can access the shared resources until the shared lock is opened at the end of the thread execution of the method. Other threads accessing the shared resource are blocked while the shared lock is not open.
The RegisterAccount class definition after thread synchronization policy control is shown in the following code:
public class RegisterAccount
{
float fBalance;
public synchronized void deposit(float fFees){ fBalance += fFees; }
public synchronized void withdraw(float fFees){ fBalance -= fFees; }
… …
}
It can be seen from the code form after the thread synchronization mechanism is defined that the synchronization definition keyword synchronized is added after the method access attribute keyword (public) for accessing shared resources, so that when the synchronization method accesses shared resources, shared locks are attached to these sensitive resources to control the resource exclusivity during the execution of the method, and the consistency management and maintenance of application system data resources are realized.
free registration
user login
Help Center
Matrix Home Matrix Dynamic Technical Column Resources Download Wonderful Recommended Website Message User Center Matrix Forum
Today is: July 16, 2003 Wednesday You are here: Home → Technology → Java Core Technology (Java Foundation Technology)
Java tutorial: parsing Java multithreading mechanism (5)
2003-6-7 Matrix keeps you moving forward Browse options: Color Default Grayscale Olive Green Blue Brown Red This article has been viewed 31 times
Java Thread Management
thread state control
What needs to be clear here is that whether you inherit the Thread class or implement the Runnable interface to implement the multithreading capability of the application, you need to define the run method used to complete the actual function in the class. This run method is called the Thread Body. According to the state of thread body in computer system memory, threads can be divided into creation, ready, running, sleep, suspended and dead. The characteristics of threads under these thread state types are:
Create state: When a thread object instance is created using the new keyword, it exists only as an object instance, and the JVM does not allocate thread running resources such as CPU time slices for it;
Ready state: Call the start method in the thread in the create state to transition the thread state to ready state. At this point, the thread has already obtained other system resources in addition to CPU time, and only waits for the thread scheduler of the JVM to schedule the thread according to the priority of the thread, so that the thread has the opportunity to obtain CPU time slices.
Sleep state: You can call the sleep method while the thread is running and specify the sleep time of the thread in the method parameters to transition the thread state to sleep. At this point, the thread stops running for the specified sleep time without releasing the hoard resources. When the time is up, the thread is rescheduled and managed again by the JVM thread scheduler.
Suspended state: You can transition a thread's state to suspended state by calling the suspend method. At this point, the thread will release all resources occupied by the JVM scheduler into temporary storage space, until the application calls the resume method to resume the thread running.
Dead state: When the thread body ends running or the stop method of the thread object is called, the thread will terminate running, and the JVM will recover the resources occupied by the thread.
In Java thread class, corresponding methods are defined respectively, which are used to control and manage thread state in application programs.
thread scheduling
Thread invocation means that JVM should coordinate multiple threads running at system level to avoid application system crash or crash caused by multiple threads competing for limited resources.
Java defines a priority policy for threads in order to distinguish between their importance to the operating system and their importance to the user. Java divides the priority of threads into 10 levels, represented by numbers between 1 and 10. Higher numbers indicate higher thread levels. Accordingly, in the Thread class, member variables MIN_PRIORITY, MAX_PRIORITY, and NORMAL_PRIORITY are defined to represent thread lowest, highest, and normal priorities, representing priority levels of 1, 10, and 5, respectively. When a thread object is created, its default thread priority is 5.
In order to control the thread execution strategy, Java defines a thread scheduler to monitor all threads in the system in a ready state. The thread scheduler determines which thread to throw into the processor according to its priority. When multiple threads are in a ready state, threads with high priority are executed before threads with low priority. Thread scheduler also uses "preemptive" strategy to schedule thread execution, that is, the thread with higher priority in the current thread execution process enters the ready state, and the thread with higher priority is immediately scheduled for execution. All threads with the same priority share CPU time slices in a round-robin fashion.
Setting thread priority in an application is simple. After creating a thread object, you can call the setPriority method of the thread object to change the running priority of the thread, and you can also call the getPriority method to get the priority of the current thread.
A special thread in Java is a low-level thread called a daemon thread. This thread has the lowest priority and serves other objects and threads in the system. The way to set a user thread as a daemon is to call the setDaemon method of the thread object before it is created. A typical example of a daemon thread is a system resource auto-reclaim thread in the JVM, which always runs in a low-level state and is used to monitor and manage reclaimable resources in the system in real time.
Thread grouping management
Java defines a ThreadGroup object in a multithreaded runtime system, which is used to implement centralized grouping management of threads according to specific functions. Each thread created by the user belongs to a thread group, which can be specified at thread creation time or not so that the thread is in the default thread group. However, once a thread joins a thread group, the thread remains in that thread group until the thread dies, and the thread group to which the thread belongs cannot be changed midway.
When a Java Application runs, the JVM creates a thread group named main. Unless specified separately, threads created in this application belong to the main thread group. In the main thread group, you can create thread groups with other names and add other threads to the thread group, and so on, forming tree management and inheritance relationships between threads and thread groups.
Similar to threads, thread group scheduling, state management, and priority setting can be performed for thread group objects. In managing thread groups, all threads that join a thread group are treated as unified objects.
Unlike other operating system environments, threads in Java runtime environment are similar to processes in multi-user, multi-task operating system environments, but processes are significantly different from Java threads in terms of how processes and threads run and are created.
Under Unix operating system environment, application program can create child process by fork function, but child process and application program process have independent address space, system resources and code execution unit, and process scheduling is completed by operating system, which makes communication and thread coordination between application processes relatively complicated. Multithreading in Java applications is multiple parallel code executors sharing the same application system resources, and the communication and coordination methods between threads are relatively simple.
It can be said that Java language's support for application multithreading enhances Java's advantages as a network programming language, and lays a solid foundation for achieving concurrent access by multiple clients in distributed application systems and improving server response efficiency.
About the implementation of Runnable interface multithreaded programming method is what to share here, I hope the above content can have some help for everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.
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.