Detailed introduction to the usage of Java multithreading

Detailed introduction to the usage of Java multithreading

The most comprehensive Java multithreading usage analysis. If you don't have an in-depth study of Java multithreading mechanism, this article can help you more thoroughly understand the principle and usage of Java multithreading.

1. Create thread

There are two ways to create threads in Java: using the thread class and using the runnable interface. When using the runnable interface, you need to create a thread instance. Therefore, whether a thread is established through the thread class or the runnable interface, an instance of the thread class or its subclass must be established. Thread constructor:

Method 1: inherit the thread class and override the run method

Method 2:

2. Thread life cycle

Like people, threads also experience four different states: start (wait), run, suspend and stop. These four states can be controlled by the methods in the thread class. The methods related to these four states are given below.

After the thread is established, it does not execute the code in the run method immediately, but is in a waiting state. When a thread is in the waiting state, you can set various properties of the thread through the method of thread class, such as thread priority (setpriority), thread name (setname), thread type (setdaemon), etc.

When the start method is called, the thread starts executing the code in the run method. The thread enters the running state. You can judge whether the thread is running through the isalive method of the thread class. When the thread is running, isalive returns true. When isalive returns false, the thread may be waiting or stopped. The following code demonstrates the switching between the three states of thread creation, run and stop, and outputs the corresponding isalive return value.

Once the thread starts executing the run method, it will not exit until the execution of the run method is completed. However, in the process of thread execution, there are two methods to make the thread temporarily stop execution. The two methods are suspend and sleep. After suspending a thread with suspend, you can wake it up with the resume method. After using sleep to make the thread sleep, the thread can only be in the ready state after the set time (after the thread sleep ends, the thread does not necessarily execute immediately, but enters the ready state and waits for the system to schedule).

There are two points to note when using the sleep method:

1. The sleep method has two overload forms. One overload form can be set not only to milliseconds, but also to nanoseconds (1000000 nanoseconds equals 1 millisecond). However, the Java virtual machine on most operating system platforms cannot be accurate to nanoseconds. Therefore, if nanoseconds are set for sleep, the Java virtual machine will take the milliseconds closest to this value.

2. When using the sleep method, you must use throws or try {...} catch {...}. Because the run method cannot use throws, only try {...} catch {...} can be used. When the interrupt method is used to interrupt a thread during thread sleep, sleep will throw an interruptedexception exception. The sleep method is defined as follows:

There are three ways to make a thread terminate.

1. Use the exit flag to make the thread exit normally, that is, when the run method is completed, the thread terminates.

2. Use the stop method to forcibly terminate the thread (this method is not recommended because stop, like suspend and resume, may also produce unpredictable results).

3. Interrupt the thread using the interrupt method.

1. Use the exit flag to terminate the thread

When the run method is executed, the thread exits. But sometimes the run method never ends. For example, threads are used in the server program to listen to client requests, or other tasks that need cyclic processing. In this case, these tasks are generally placed in a loop, such as a while loop. If you want the loop to run forever, you can use while (true) {...} to handle it. However, the most direct way to make the while loop exit under a specific condition is to set a boolean flag and control whether the while loop exits by setting this flag to true or false. An example of terminating a thread with an exit flag is given below.

The function of the join method is to turn the thread executing asynchronously into synchronous execution. That is, after calling the start method of the thread instance, this method will return immediately. If you need to use a value calculated by this thread after calling the start method, you must use the join method. If you don't use the join method, you can't guarantee that when you execute a statement after the start method, the thread will finish executing. After using the join method, the program will not execute until the thread exits. The following code demonstrates the use of join.

3. Multithreading security issues

Problem reason: when multiple statements are operating on the same thread to share data, one thread only partially executes multiple statements, but another thread participates in the execution, resulting in the error of sharing data.

Solution: for statements with multiple operations sharing data, only one thread can be executed. During execution, other threads will not execute.

Sync code block:

Synchronization function

The synchronization function lock is this, and the static synchronization function lock is class

Communication between threads

Modify the above code

Wait for wake-up mechanism

Production and consumption mechanism I

Production and consumption mechanism 2

The above is how to use Java multithreading. If you have any questions, please leave a message or go to the community of this site for communication and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>