This article describes the example of Java using Thread to create multi-threading and start operations. Share it for your reference, as follows:
According to the tutorial, a single thread was created, but the creation of a single thread at startup is not very practical. After all, putting relevant execution operations directly in the main method is a single thread implementation. Next, make a little modification based on the previously used code to form the following code:
class ThreadDemo extends Thread{ ThreadDemo(){}; ThreadDemo(String szName) { super(szName); } public void run() { int i = 0; for(i = 0;i < 10;i++) { System.out.println("run" + (i + 1) + " times"); } } public static void main(String[] args) { ThreadDemo demo1 = new ThreadDemo(); ThreadDemo demo2 = new ThreadDemo(); ThreadDemo3 = new ThreadDemo(); demo1.start(); demo2.start(); demo3.start(); }}The code compilation and running results are as follows;
E:/WorkSpace/02_Technical Practice/01_Programming Language/05_Java/02_Java From Beginner to Mastery/thread_demo>javac ThreadDemo.java
E:/WorkSpace/02_Technical Practice/01_Programming Language/05_Java/02_Java From Beginner to Mastery/thread_demo>java ThreadDemo
run 1 times
run 2 times
run 3 times
run 4 times
run 5 times
run 6 times
run 7 times
run 1 times
run 2 times
run 1 times
run 3 times
run 8 times
run 4 times
run 2 times
run 5 times
run 9 times
run 6 times
run 7 times
run 8 times
run 3 times
run 9 times
run 10 times
run 10 times
run 4 times
run 5 times
run 6 times
run 7 times
run 8 times
run 9 times
run 10 times
From the above results, we actually see a certain out of order, and it seems that the execution order of the three tasks is not in order. In fact, this is the result of the three created threads that have competed in execution.
I was really a little stupid when I was writing programs. Although I have completed the task for so long, what I have implemented before was single-threaded work. A task is executed from beginning to end, but fortunately, the execution speed of the computer is not bad, otherwise I would have wasted much execution time!
Although I am learning Java now, I should try to use this function in later languages such as Python that support multi-threading. It is still very interesting to tap the CPU potential as much as possible.
For more Java-related content, readers who are interested in this site can view the topics: "Summary of Java Process and Thread Operation Skills", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.