Creation of Threads
1. Two ways to create a thread
(1) Create a subclass of thread and overwrite the run () method
(2) Implement Runnable interface
Ways to create multithreading
Method 1: implement multi-threading by creating a subclass of the thread class, steps like this:
1. Define a subclass of the thread class.
2. Define a method in the subclass run (), overwriting the method run () in the parent class.
3. Create a thread object for the subclass.
4. Start the thread with the start () method.
Note :
1. Each thread will start and each thread will run until it is complete.
2. A series of threads starting in some order does not mean that they will be executed in that order.
3. For any thread that starts, the scheduler cannot guarantee its execution order, and the duration is not guaranteed.
4. When the thread target run () method ends, the thread finishes
Method 2: Create multi-Threading through an interface, with the following steps:
1. Define a class that implements the Runnable interface.
2. Define the method run (). The runnable interface has an empty method run (), and the class that implements it must override this method.
3. Create a thread object for the class, and pass the object as a parameter to the constructor of the thread class to produce an object of the thread class. Watch this step!
4. Start the thread with the start () method.
Note : Because Java does not allow multiple inheritance, the first method can only be used if the class does not extend any other class. Therefore, for many extension classes that are already other classes (such as applet programs), only the second method can be used to create threads.
Creation and basic use of Java threads