A closer look at the right and wrong ways to start threads in Java
A closer look at the correct and incorrect ways to start threads in Java
Review of the previous article
- Detailed analysis of the methods of implementing multi-threading in Java are How many? (Based on the essence)
Comparison of start method and run method
Code demonstration:
/** * <p> * start() 和 run() 的比较 * </p> * * @author 踏雪彡寻梅 * @version 1.0 * @date 2020/9/20 - 16:15 * @since JDK1.8 */public class StartAndRunMethod { public static void main(String[] args) { // run 方法演示 // 输出: name: main // 说明由主线程去执行的, 不符合新建一个线程的本意 Runnable runnable = () -> { System.out.println("name: " + Thread.currentThread().getName()); }; runnable.run(); // start 方法演示 // 输出: name: Thread-0 // 说明新建了一个线程, 符合本意 new Thread(runnable).start(); } }复制代码
From the above example The following two points can be analyzed:
Directly using the
run
method will not start a new thread. (wrong way)start
method starts a new thread. (Correct way)
start method analysis
The meaning of the start method and precautions
start
method can start a new thread.- After the thread object calls the
start
method after initialization, the current thread (usually the main thread) will request the JVM virtual machine to start this if it is free. New thread. - In other words, the essence of starting a new thread is to request the JVM to run the thread.
- As for when this thread can run, it is not simply decided by us, but by the thread scheduler.
- If it is very busy, even if we run the
start
method, we may not be able to start the thread immediately. - So after the
srtart
method is called, it does not mean that this method has started running. It may not run until later, or it may not run for a long time, such as in case of starvation. - This also proves that in some cases, thread 1 first calls the
start
method, and then thread 2 calls thestart
method, only to find that thread 2 first The situation of execution after executing thread 1. - Summary: The order in which the
start
method is called does not determine the order in which the actual threads are executed. - Note
start
method will involve two threads.- The first one is the main thread, because we must have a main thread or other threads (even if it is not the main thread) to execute this
start
method, the second one is the new one the rout. - In many cases, the main thread that creates the thread for us will be ignored. Don't mistakenly think that calling
start
is already executed by the child thread. This statement is actually the main thread or the main thread. It is executed by the parent thread, and a new thread is created after it is executed.
- After the thread object calls the
start
Method to create a new thread preparations- First, it will make itself In ready state.
- The ready state means that other resources besides the CPU have been obtained, such as the context, stack, thread status and PC (PC is a register, PC points to the location where the program is running), etc. have been set.
- After completing these preparations, everything is ready and all you need is Dongfeng, which is the CPU resource.
- After completing the preparation work, the thread can be further scheduled by the JVM or operating system to the execution state to wait for CPU resources, and then it will actually enter the running state to execute the
run
method. code.
- First, it will make itself In ready state.
Note: The start method cannot be executed repeatedly
Code example
/** * <p> * 演示不能重复的执行 start 方法(两次及以上), 否则会报错 * </p> * * @author 踏雪彡寻梅 * @version 1.0 * @date 2020/9/20 - 16:47 * @since JDK1.8 */public class CantStartTwice { public static void main(String[] args) { Runnable runnable = () -> { System.out.println("name: " + Thread.currentThread().getName()); }; Thread thread = new Thread(runnable); // 输出: name: Thread-0 thread.start(); // 输出: 抛出 java.lang.IllegalThreadStateException // 即非法线程状态异常(线程状态不符合规定) thread.start(); } }复制代码
Copy after loginCause of error
start
Once execution starts, the thread state will enter the subsequent state from the initial New state, such as Runnable, and then Once the thread completes execution, the thread will become a terminated state, and the terminated state can never be returned, so the above exception will be thrown, which means that it cannot return to the initial state. The description here is not clear enough. Let's take a look at the source code to understand more thoroughly.
start method source code analysis
Source code
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ // 第一步, 检查线程状态是否为初始状态, 这里也就是上面抛出异常的原因 if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ // 第二步, 加入线程组 group.add(this); boolean started = false; try { // 第三步, 调用 start0 方法 start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } }复制代码
Process in the source code
Step one: When starting a new thread, it will first check whether the thread state is the initial state, which is also the reason why the above exception is thrown. That is, the following code:
if (threadStatus != 0) throw new IllegalThreadStateException();复制代码
Among them, threadStatus
The annotation of this variable is as follows, which means that the Java thread status is initially expressed as 0 (not yet started):
/* Java thread status for tools, * initialized to indicate thread 'not yet started' */private volatile int threadStatus = 0;复制代码
Step 2:Add it to the thread group. That is, the following code:
group.add(this);复制代码
The third step:Finally call start0()
This native method (native means that its code is not implemented by Java, but by C/C implementation, the specific implementation can be seen in the JDK, just understand it), that is, the following code:
boolean started = false;try { // 第三步, 调用 start0 方法 start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } }复制代码
run method analysis
run method source code analysis
@Overridepublic void run() { // 传入了 target 对象(即 Runnable 接口的实现), 执行传入的 target 对象的 run 方法 if (target != null) { target.run(); } }复制代码
Two situations for the run method
The first one: Overriding the
run
method of theThread
class,Thread
'srun
method will be invalid, and the overriddenrun
method will be executed.Second type: Pass in the
target
object (that is, the implementation of theRunnable
interface) and execute the original # ofThread
The ##runmethod then proceeds to execute the
runmethod of the
targetobject.
- Summary: The
- #run
method is an ordinary method. The
runmethod is directly executed above. It is equivalent to executing the ordinary method we wrote ourselves, so its execution thread is our main thread.
So if you want to actually start the thread, you cannot call the - run
method directly, but you must call the
startmethod, in which you can call
run## indirectly. # method.
- #run
Related learning recommendations:
The above is the detailed content of A closer look at the right and wrong ways to start threads in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
