Java inheritance thread class creates multithreaded single-threaded samples
Example, Example01.java
public class example01{public
static void Main (string[] args) {
//Create Mythread Instance object
//Invoke the Mythread class run () Method in Run
//The loop is a dead loop, the printout statement
mythread mythread=new mythread ();
Mythread.run ();
while (true) {
System.out.println ("Main method is running");
}} Class mythread{public
void Run () {
while (true) {
//The loop is a dead loop, the printout statement
System.out.println (" The run () method of the Mythread class is running ");}}
Compile run
As you can see, the program has been printing the Mythread class's Run () method
Because the sequence is a single-threaded program, when the Mythread class's run () method is invoked, a dead loop is encountered, and so the Mythread class print statement, which will always execute in the main () method of the print statement, cannot get the execution of a multithreaded sample
If you want the print statements in the two while loop to execute concurrently, you need to implement multithreading
To do this, a thread class thread is provided in the JDK, and multithreading can be achieved by inheriting the thread class and overriding the run () method in the Thread class
In the thread class, a start () method is provided to start a new thread, and the system automatically calls the run () method after the thread starts
Example, Example02.java
public class example02{public
static void Main (string[] args) {
//Create thread Mythread Thread object
//Open thread
// Print out
mythread mythread=new mythread () through dead loop statements;
Mythread.start ();
while (true) {
System.out.println ("main () method is running");
}} Class Mythread extends thread{public
void Run () {while
(true) {
System.out.println ("Mythread class's Run () Method is running ");}}}
Compile run
As you can see, the print statements in the two while loop are executed in turn, indicating that the example implements multithreaded single-threaded
When the program is running, it executes multithreading in the order in which the code is called
The main () method and the Run () method of the Mythread class can be executed concurrently, without affecting