The difference between start method and run method in java thread is introduced in detail

The difference between start method and run method in thread

In the thread, if the start method calls the run method in turn, why do we choose to call the start method? Or where is the difference between calling start method and run method in java thread? These two questions are two very popular multithreaded interview questions at the beginner level. When a Java programmer starts learning threads, they first learn to inherit the Thread class, override the run method or implement the Runnable interface, implement the run method, and then invoke the start method of the Thread instance. However, after he has some experience, he will find that the run method will be called inside the start method by looking at the API documents or other ways, but many of us will realize the importance of this question only when we are asked during the interview. In this java tutorial, we will understand the difference between calling the start method and the run method when starting a thread in Java

E.g. difference between runnable and thread in Java and how to solve producer consumer problem in Java using BlockingQueue If you haven't read them, you may find them interesting and useful

The difference between start and run in Java threads

The main difference between start and run methods is that when the program calls the start method, a new thread will be created, and the code in the run method will run on the new thread. However, when you call the run method directly, the program will not create a new thread, and the code inside the run method will run on the current thread. In most cases, calling the run method is a bug or becomes an error. Because the caller's original intention is to call the start method to start a new thread, this error can be detected by many static code coverage tools, such as fingbugs If you want to run a task that takes a lot of time, you'd better use the start method, otherwise your main thread will get stuck when you call the run method. Another difference is that once a thread is started, you cannot call the start method of the thread object repeatedly. Calling the start method of the started thread will report an IllegalStateException exception, but you can call the run method repeatedly

The following is a demo of the start method and run method

The task in the thread is to print the string value passed in by the thread and the name of the current thread

Here you can clearly see the difference between the two

Thank you for reading, hope to 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
分享
二维码
< <上一篇
下一篇>>