Thread (reproduced)

xiaoxiao2021-03-06  59

Java multi-thread programming 1/2 (repost) 1: understand multithreading

Multithreading is a mechanism that allows multiple instruction streams to be executed in the program, each instruction stream is called a thread, which is independent of each other.

Threads are also known as lightweight processes, which have independent execution control as the process, and the * is responsible for the system, the difference is that the thread has no independent storage, but shares a storage space with other threads in the process, this The communication between the thread is far from the process.

The execution of multiple threads is concurrent, that is, "simultaneously" logically, regardless of whether it is physical "simultaneous". If there is only one CPU, then the real "simultaneous" is impossible, but because the speed of the CPU is very fast, the user does not feel the difference, so we don't have to care about it, only need to envisure the threads simultaneously .

Multi-threaded and traditional single-threading in programming the biggest difference is that since the control flows of each thread are independent of each other, the code between each thread is executed, resulting in thread scheduling, synchronization, etc. It will be discussed later.

2: Implement multithreading in Java

We may wish to think about what we need to do in order to create a new thread? Obviously, we must indicate the code to be performed by this thread, and this is everything we need to do in Java!

It's amazing! How does Java do this? By class! As a full-scale object, Java provides class java.lang.Thread to facilitate multi-threaded programming, which provides a large number of ways to facilitate our control of our threads, and we will be carried around this class.

So how do you provide the code we want to thread to java? Let's take a look at the Thread class. The most important way to THREAD class is Run (), which is called for the Thread class, and provides the code to be performed by our thread. In order to specify our own code, just override it!

Method 1: Inheriting the Thread class, coverage method Run ()

We rewrite Run (), join the code to be executed in the subclass of the Thread class. Below is an example:

Public class mythread extends thread {int count = 1, Number; public mythread (int Num) {Number = Num; system.out.println ("Create Thread" Number); System.out.println ("Thread" Number ": Count" Count); if ( Count == 6) Return;}} public static void main (string args []) {for (int i = 0 i <5; i ) New Mythread (i 1) .start ();}}

This method is simple and clear, in line with everyone's habits, but it also has a big shortcoming, that is, if our class has inherited from a class (such as a small program must inherit from the Applet class), you can't inherit the Thread class. At this time, if we don't want to build a new class, what should I do?

We may wish to explore a new way: we don't create a subclass of the Thread class, but use it directly, then we can only pass our method as a parameter to the Thread class instance, a bit similar to the callback function. But Java does not have a pointer, we can only pass an instance of classes that contain this method. So how do you limit this class to include this method? Of course, use the interface! (Although the abstract class can also be satisfied, it is necessary to inherit, and we have to use this new method, isn't it to avoid inheritance?) Java provides interface java.lang.Runnable to support this method.

Method 2: Implement Runnable interface

The RunNable interface has only one method run (), we declare that our class implements the runnable interface and provides this method, and write our thread code to the task of this part.

But the runnable interface does not have any support for threads, and we must also create an instance of the Thread class, which is implemented through the constructor of the Thread class.

Below is an example:

Public class mythread implements runnable {int count = 1, number; public mythread (int Num) {Number = NUM; System.out.Println ("Create Thread" Number); System.out.println ("Thread" Number ": Count" Count); if ( Count == 6) Return;}} public static void main (string args []) {for (int i = 0 i <5; i ) New Thread (New Mythread (i 1)). start ();}}

Strictly speaking, an example of creating Thread subclasses is also possible, but it must be noted that the subclass must not cover the RUN method of the Thread class, otherwise the thread will be the RUN method of the subclass, not me

They use the RUN method of the class of the runnable interface, you may wish to test it.

Using the runnable interface to implement multithreading makes us to include all the code in a class, which is conducive to the package, it's a disadvantage that we can only use a set of code, if you want to create multiple threads and make each thread perform different code The classes must still be created additionally. If this is, in most cases, it is better to inherit Thread is compactly with multiple classes in most cases.

In summary, both methods have a thousand autumn, everyone can be flexible.

Let's take a look at some of the problems in multi-threaded use.

Three: four states of thread

1. New Status: The thread has been created but has not been executed (start () has not been called).

2. Execute Status: Threads can be executed, although not necessarily being implemented. The CPU time may be assigned to the thread at any time, making it execute.

3. Death Status: Run () returns the thread to death. Calling STOP () or destroy () also has the same effect, but it is not recommended, the former will produce an exception, the latter is forced to terminate and does not release the lock.

4. Blocking Status: The thread will not be assigned a CPU time and cannot be executed. 4: Thread priority

The priority of the thread represents the importance of the thread. When multiple threads are in executable and wait for the CPU time, the thread scheduling system determines the priority of each thread to assign CPU time, high priority. There is a greater chance to get the CPU time, the priority low thread is not there, just the opportunity to be small.

You can call the Thread class method getPriority () and setPriority () to access the thread priority, the thread is between 1 (Min_Priority) and 10 (Max_Priority), default is 5 (Norm_Priority).

Five: Synchronization of threads

Since multiple threads of the same process share the same storage space, it also brings convenience, it also brings a serious problem of accessing conflicts. The Java language provides a special mechanism to address this conflict, effectively avoiding the same data objects to be accessed simultaneously by multiple threads.

Since we can guarantee data objects through the private key, we can only be accessed by way, so we only need to make a set of mechanisms for the method, this mechanism is the synchronized keyword, which includes two usage: Synchronized method and Synchronized block.

1. Synchronized method: Declare the Synchronized method by adding the synchronized keyword in the method declaration. Such as:

Public Synchronized Void AccessVal;

Synchronized method controls access to class member variables: Each class instance corresponds to a lock, each Synchronized method must obtain the lock of the class instance of the method that calls the method, otherwise the thread is blocked,

Once the law is performed, the lock is exclusively until it will be released until it returns from this method, and the block is blocked, and the lock can be re-entered. This mechanism ensures that at the same time for each class instance, all of which is in the member function of Synchronized, is in an executable state (because at most one can get the corresponding lock), effectively avoid the class member. Variables Access Conflict (as long as all methods that may access class member variables are declared as synchronized).

In Java, not only a class instance, each class also corresponds to a lock so that we can also declare the class's static member function as synchronized to control its access to the static member variables of the class. Synchronized method: If a big method declares that Synchronized will greatly affect efficiency, typically, if the thread type method Run () is declared as synchronized, since it has been running during the entire life of the thread, It will lead to the call to any SYNCHRONIZED method in this class will never succeed. Of course, we can declare this issue by placing the code of the access class member variables in a special method, and call this problem in the main method, Java provides us with better solution, that is SYNCHRONIZED block.

2. Synchronized block: Declare the Synchronized block by synchronized keyword. The syntax is as follows: synchronized (syncobject) {// Allows access control code / R}

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

New Post(0)