Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the preliminary design method of Java multithreaded program?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the preliminary design method of Java multithreaded program". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the preliminary design method of Java multithreaded program?"

Before the emergence of the Java language, the programs of the traditional programming language could only operate on a single task at the same time, and the efficiency was very inefficient. For example, the program was often blocked when receiving data input, and could not continue to run until the program obtained the data. With the rapid development of Internet, this situation is becoming more and more unbearable: if the network receives data blocking, the background program will wait and do not continue any operation, and this blocking is often encountered, when CPU resources are idle in vain. It would be nice to be able to handle multiple tasks at the same time in the daemon! Java language, which comes from Internet technology, solves this problem. Multithreaded program is a very important feature of Java language. In a Java program, we can run multiple relatively independent threads in parallel at the same time, for example, if we create one thread for data input and output, and another thread for other data processing in the background, if the input and output thread blocks while receiving the data, and the thread processing the data is still running. Multi-thread programming greatly improves the execution efficiency and processing ability of the program.

Creation of threads

We know that Java is an object-oriented programming language, programming with Java is to design and use classes, Java provides us with thread class Thread to create threads, the operation of creating threads is the same as creating objects of ordinary classes, and threads are instance objects of the Thread class or its subclasses. The following is a statement that creates a thread to start:

Thread thread1=new Thread (); file:// declares an object instance, that is, creates a thread; Thread1.run (); file:// starts the thread with the run () method in the Thread class

From this example, we can create a thread through the Thread () constructor and start it. In fact, starting a thread, that is, the run () method of starting a thread, while the run () method in the Thread class does not have any operation statements, so this thread does not have any operations. For a thread to perform a predetermined function, you must define its own run () method. There are usually two ways to define the run () method in Java:

Override the run () method in a subclass of the Thread class by defining it. The instance object of the Thread subclass is a thread. Obviously, the thread has our own thread body run () method, and starting the thread starts the run () method overridden in the subclass.

Through the Runnable interface, the interface of the run () method is defined in that interface. The so-called interface is very similar to classes, mainly used to implement special functions, such as multiple inheritance of complex relationships. Here, we define a class that implements the Runnable () interface, define its own run () method in the class, and then call the constructor of the Thread class as a parameter to create a thread.

The thread is in a standby state after it is actually created. Activating (starting) the thread is the run () method of the startup thread, which is achieved by calling the thread's start () method.

The following example practices how to create threads and start them using the above two methods:

/ / threads created by subclasses of the Thread class; class thread1 extends Thread {file:// custom thread's run () method; public void run () {System.out.println ("Thread1 is running …") ;}} another thread created by file:// through the Runnable interface; class thread2 implements Runnable {run () method of the file:// custom thread; public void run () {System.out.println ("Thread2 is running …") ;} the main class of the file:// program 'class Multi_Thread file:// declares the main class; {plubic static void mail (String args []) file:// declares the main method; {thread1 threadone=new thread1 (); file:// creates a thread with a subclass of the Thread class; Thread threadtwo=new Thread (new thread2 ()); file:// creates a thread with the object of the Runnable interface class Threadone.start (); threadtwo.start (); file://strat() method to start the thread;}}

When you run the program, you can see that threads threadone and threadtwo alternately occupy CPU and are running in parallel. As you can see, the run () method of starting a thread is implemented by calling the thread's start () method (see the main class in the example above). The run () method of calling the start () method to start the thread is different from the general calling method. When a general method is called, the start () method cannot be returned until the execution of the general method is completed, but after the thread's run () method is started After start () tells the system that the thread is ready to start the run () method, it returns the start () method to execute the statement below the statement that calls the start () method, and the run () method may still be running, so that the thread starts and runs in parallel, realizing multitasking operations.

Priority of the thread

For multithreaded programs, the importance of each thread is different, for example, when multiple threads are waiting for CPU time, we often need high-priority threads to preempt CPU time for execution; and for example, when multiple threads execute alternately, priority determines how many times and how long a high-level thread gets CPU; in this way, high-priority threads are more efficient in processing tasks.

The priority of a thread in Java is represented by the integer 1x 10, which is divided into 10 levels. The priority is set by calling the setPriority () method of the thread object. As in the example above, the statement that sets the priority is:

Thread1 threadone=new thread1 (); file:// creates a thread with a subclass of the Thread class; Thread threadtwo=new Thread (new thread2 ()); file:// creates a thread with an object of the Runnable interface class; threadone.setPriority (6); file:// sets the priority of threadone (3); file:// sets the priority of threadtwo (3); threadtwo.start (); the file://strat() method starts the thread

In this way, thread threadone will take precedence over thread threadtwo execution and will take more CPU time. In this example, the priority setting is placed before the thread starts, or it can be set after startup to meet different priority requirements.

(synchronization) control of threads

Data can be shared among multiple threads of a Java program. When threads access shared data asynchronously, it is sometimes insecure or illogical. For example, at the same time, one thread is reading the data, and another thread is processing the data. When the thread processing the data does not wait for the reading thread to finish reading the data, it is bound to get the wrong processing result. This is not contradictory to the parallel multitasking of reading and processing data mentioned earlier, which means that the thread that processes the data cannot process the data that has not yet been read, but can process other data.

If we use the multi-thread synchronization control mechanism, the error will not be avoided until the second thread can process the data after * thread has finished reading the data. It can be seen that thread synchronization is a very important technology in multithreaded programming.

Before we talk about thread synchronization control, we need to explain the following concepts:

1. The method of synchronizing the operation of shared data with the Java keyword synchonized

In an object, the method declared with synchonized is a synchronous method. There is a synchronization model in Java, the monitor, which is responsible for managing thread access to synchronization methods in an object. Its principle is: give the object a 'key'. When multiple threads enter the object, only the thread that acquires the object key can access the synchronization method, and other threads wait in the object until the thread abandons the key with the wait () method, and other waiting threads seize the key The thread that preempts the key can be executed, while the thread that does not get the key is still blocked and waiting in the object.

A way for file:// to declare synchronization: synchronize method declarations

Class store {public synchonized void store_in () {… Public synchonized void store_out () {… .}}

two。 Using wait (), notify () and notifyAll () methods to send messages to realize the interconnection between threads.

Multiple threads in the Java program interact with each other through messages, and these methods realize the sending of messages between threads. For example, if you define the synchonized method of an object, only one thread can access the synchronization method in the object at a time, and other threads are blocked. You can usually wake up one or all other threads with the notify () or notifyAll () methods. Instead, use the wait () method to block the thread and wait for other threads to wake up with notify ().

A practical example is production and sales, where the production unit produces the product and puts it in the warehouse, while the sales unit takes the product from the warehouse. In this process, the sales unit can only pick up the goods when there are products in the warehouse; if there are no products in the warehouse, the sales unit must wait.

In the program, if we define a warehouse class store, the instance object of this class is equivalent to the warehouse, and two member methods are defined in the store class: store_in (), which is used to simulate the product manufacturer to add products to the warehouse; and the strore_out () method is used to simulate the seller to take the product from the warehouse. Then two thread classes are defined: the customer class, where the run () method simulates the seller by calling store_out () in the warehouse class; and the run () method in the other thread class producer impersonates the product manufacturer by calling the store_in () method in the warehouse class to add products to the warehouse. Create and start threads in the main class to add or remove products to the warehouse.

If the store_in () and store_out () methods in the repository class do not declare synchronization, this is a general multithreading. We know that multithreads in a program are executed alternately and run out of order, so there may be such a problem:

There is no product in the warehouse, and the seller is still patronizing and "fetching" the product, which is meaningful in reality and negative in the program. If the stroe_in () and store_out () methods in the warehouse class are declared to be synchronized, as shown in the above example: it controls that only one thread can access the synchronization method in the warehouse object at a time. That is, when a production thread accesses the store_in () method that is declared to be synchronized, other threads will not be able to access the store_out () synchronization method in the object, and certainly not the store_in () method. You must wait until the thread calls the wait () method to discard the key before other threads have a chance to access the synchronization method.

This principle is also easy to understand in practice. When the producer (producer) gets the key of the warehouse, he adds the product to the warehouse. At this time, it is impossible for other sellers (customer, which can be one or more) to obtain the key. Only when the producer has finished adding the product, return the key and notify the seller, different sellers decide whether they can enter the warehouse to pick up the product according to the order of obtaining the key.

At this point, I believe that everyone on the "Java multithreaded program preliminary design method is what" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report