Java multi-threaded program entry

xiaoxiao2021-03-06  79

Before the Java language is generated, the traditional programming language program can only be single task operation at the same time, and the efficiency is very low. For example, the program is often blocked when the data is received, and only the program is allowed to obtain the data before running. With the rapid development of the Internet, this situation is increasing to endure: If the network receives data blocked, the background program is waiting state without continuing any operation, and this blocking is often encountered, at this time CPU The resource is idle in white. If you can handle multiple tasks at the same time in the background program, how good! The Java language, which should be born in Internet technology, solves this problem, multithreading program is a very important feature of the Java language. In a Java program, we can run multiple relatively independent threads at the same time, for example, if we create a thread to perform data input and output, create another thread to do other data processing in the background, if the input and output thread is received The data is blocked, and the thread that handles the data is still running. Multi-threaded programming greatly improves program execution efficiency and processing power.

Creation of thread

We know that Java is an object-oriented programming. It is designed with Java to design and use classes. Java provides us with thread thread to create threads, creating a thread is the same as an object of creating a normal class, and thread It is the example object of the Thread class or its subclass. Below is a statement that creates a thread:

Thread thread1 = new thread (); file: // Declare an object instance, creating a thread;

Thread1.run (); file: // Start the thread with the Run () method in the THREAD class;

From this example, we can create a thread through the thread () constructor and start the thread. In fact, start the thread, that is, the RUN () method of the thread is started, and the Run () method in the Thread class does not have any operational statements, so this thread does not have any operation. To make the thread implement a predetermined function, you must define your own Run () method. There are usually two ways to define the Run () method in Java:

Reword the Run () method in the subclass by defining a subclass of a Thread class. The example object of the Thread subclass is a thread, apparent that the thread has our own thread body Run () method, and the start thread starts the Run () method rewritten in the subclass.

The interface of the RUN () method is defined in the interface through the Runnable interface. The so-called interface is very similar, mainly used to achieve special functions, such as multiple inheritance functions of complex relationships. Here, we define a class that implements the runnable () interface, defines its own Run () method in this class, and then call the Thread class constructor to create a thread with the instance object of this class.

The thread is actually created after a standby state, and the activation (start) thread is the RUN () method that starts the thread, which is implemented by calling the string START () method.

One of the following examples practices how to create threads through both methods and launch them:

// Thread created by the subclass of the Thread class;

Class Thread1 Extends Thread

{File: / / Custom Run () method of the thread;

Public void Run ()

{

System.out.println ("Thread1 IS Running ...");

}

}

File: // Different threads created by the runnable interface;

Class Thread2 IMPLEMENTS RUNNABLE

{File: / / Custom Run () method of the thread;

Public void Run ()

{

System.out.println ("Thread2 Is Running ...");

}

}

File: // Program's main class'

Class Multi_thread File: // Declare the main class;

{

Plubic Static Void Mail (String Args []) File: // Declare the main method;

{

Thread1 threadOne = new thread1 (); file: // creates a thread with the subclass of the Thread class;

Thread threadtwo = new thread (new thread2 ()); file: // creates a thread with an object of the Runnable interface class;

ThreadONE.Start (); threadtwo.start (); file: // strat () method launches the thread;

}

}

It can be seen that thread ThreadOne and ThreadTWO are alternately occupying the CPU. It can be seen that the RUN () method of the starting thread is to be implemented by calling the string START () method (see the primary class in the previous example), call the start () method to start the thread's Run () method is different from the general call method. When calling a general method, it is necessary to wait until the general method is executed to return the start () method, and after startling the thread, start () tells the system that the thread is ready to start the Run () method, return START. () Method Execute the statement below the Start () method statement, then the run () method may be running, so that the startup and running parallel of the thread are performed, and multi-tasking operations are implemented.

Thread priority

For multi-threaded programs, the importance of each thread is different. If multiple threads are waiting for CPU time, we often need priority high thread priority to grab the CPU time to execute; another thread alternately At the time, the priority determines that the number of high-level threads gets more than the number of CPUs and is more time; so that the task efficiency of the high priority thread processing is high.

The priority of the thread in Java is represented by an integer from 1 to 10, a total of 10 levels, and the setting priority is a setPriority () method of the thread object, as in the above example, set the priority statement as:

Thread1 threadOne = new thread1 (); file: // creates a thread with the 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: // Set the priority of ThreadOne 6;

ThreadTwo.SetPriority (3); file: // Set the priority 3 of ThreadTWO;

ThreadONE.Start (); threadtwo.start (); file: // strat () method launches the thread;

Thus, thread ThreadOne will take precedence over thread THREADTWO and will have more CPU times. In this example, the priority setting is placed before the thread is started, or it can be set after starting to meet different priority requirements.

Threaded (synchronous) control

You can share data between multi-threads of a Java program. When threads access shared data in asynchronously, sometimes it is unsafe or not logical. For example, the same time is a thread in reading data, and another thread is handling data. When processing data thread does not wait until the thread read of the data is read, the data will be dedupted. This is not contradictory with the read data and processing data mentioned earlier, which refers to the process of processing data that cannot be handled, but other data can be processed. If we use multi-threaded synchronous control mechanisms, wait until the first thread reads data, the second thread can handle the data, will avoid errors. It can be seen that thread synchronization is a fairly important technique for multi-threaded programming.

We need to explain the following concept before the synchronization of threads:

1 Method for synchronizing the shared data operation with Java Keyword Synchonized

In an object, the method declared with the synchonized declaration is a synchronous method. There is a synchronous model in Java, which is responsible for managing access to the synchronization method in the object. It is: Give the object unique 'key', when multiple threads enter the object, only the object key is obtained The thread can access the synchronization method, and other threads are waiting in the object until the thread uses the Wait () method to give up this key, the other waiting threads will take the key, grab the key to the thread, but no The thread that acquires the key is still blocked in this object.

File: // Declare synchronization: State the method to synchronize

Class Store

{

Public synchonized void store_in ()

{

.

}

Public synchonized void store_out () {

}

}

2 Use Wait (), Notify () and NotifyAll () methods to send messages to implement the internet access

Multiple threads in the Java program communicate interact with messages, and these methods implements messaging between threads. For example, a SYNCHONIZED method of an object is defined, and only one thread can access the synchronization method in the object at the same time, and other threads are blocked. Other or all threads can usually be awaken with the notify () or notifyall () method. The WAIT () method is used to cause the thread to block the block, waiting for other threads to wake up with notify ().

A actual example is production and sales, and the production unit produces products in the warehouse, and the sales unit takes the product from the warehouse. In this process, the sales unit must be available when there is a product in the warehouse; if the warehouse No product, 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, defining two members methods in the Store class: store_in (), used to add products to the warehouse; Strore_out () The method is used to simulate sellers to take the product from the warehouse. Then define two thread classes: Customer class, where the Run () method takes away the product from the warehouse class, simulates the salesperson from the warehouse, and simulates the salesman; another thread class set () method in the Run () method is called the warehouse The Store_in () method in the class adds a product to the warehouse and analog product manufacturer. Create and start the thread in the primary class, implement the product to the warehouse or take the product.

If the Store_in () and the store_out () method in the warehouse class do not declare synchronization, this is a general multi-thread, we know that multi-thread in a program is alternate, running is also unordered, so that there may be Such a problem:

There is no product in the warehouse, the seller is still constantly patron, but also keeps in 'product, this is unborn in reality, and it behaves as a negative value in the program; () And store_out () methods Declare synchronization, as shown in the above example: Controlling the same time can only have a synchronization method in the warehouse object; that is, a production class thread access is declared as a Synchronous Store_in () method, Other threads will not be able to access the Store_Out () synchronization method in the object, and of course you cannot access the store_in () method. You must wait until the thread calls the WAIT () method to abandon the key, and other threads have the opportunity to access the synchronization method. This principle is actually very well understood that when producers get the only key to the warehouse, add products to the warehouse. At this time, other sellers (Customer, one or more) cannot obtain the key, Only when the producer has ended, the key is returned and the seller is notified. Different sellers decide whether to enter the warehouse in the warehouse according to the success of the key.

转载请注明原文地址:https://www.9cbs.com/read-107629.html

New Post(0)