One way to create multiple threads in java:

//Multi-thread creation:
//Method 1: Create a method inherited from the Thread class
//1, create a subclass that inherits the Thread class
//2, override the run() method in the Thread class -> this The operation performed by the thread is written in the run method
//3, the object of the subclass of the Thread class is created
//4, the start() is called through the subobject

The following is a specific example:
Insert picture description here
as can be seen from the main method main, we created an object, and then passed, the object calls the start() method in the Thread class, and creates another thread from m.start(). And the following method is actually executed in the main thread, we can verify:
Insert picture description here
through the execution result, we can see that the name of the parent class that our object calls the start method to execute is Thread, and the for loop in the main method is executed as main; therefore Two threads are executed at the same time (the results of each person running this code may be different, the reason is: each person's computer performance is different, the main frequency of the cpu is different); the most important point is the main method An object can only execute the start method once. If an object executes the start method multiple times in the main method, an error will be reported, as shown in the figure below: if you
Insert picture description here
don’t understand it, continue to look at the figure below: the
Insert picture description here
source code shows that the start() method is the same The object can only be called once. If the same object is called multiple times, an exception will be reported, that is, Exception in thread “main” java.lang.IllegalThreadStateException! !

Anything wrong, please correct me! ! !

Guess you like

Origin blog.csdn.net/m0_46228439/article/details/110768413