Java provides two ways to create a thread:
Here we only take the Runnable interface as an example:
package concurrency;public class test1 { public static Void main (String[] args) { for (int i = 1; i <= 10; i++) { calculator calculator = new calculator (i); thread thread = new thread (Calculator); thread.start (); } }}class calculator implements runnable { private int number; public calculator (int Number) { this.number = number; } @Override public void run () { for (int i = 1; i <= 10; i++) { system.out.printf ("%s: %d * %d = %d\n ", thread.currentthread (). GetName (), Number,i,i*number); } }}
When the start () method of the thread object is called, another thread of execution is created. Thus, in our program, each time the start () method is called, an execution thread is created.
When all the threads of a program are running, it is more clear that the Java program will end when all non-daemon (Non-daemon) threads are complete. If the initial thread (the thread that executes the main () method) ends, the remaining threads will continue to execute until they run to the end. If a thread calls the System.exit () directive to end the execution of the program, all threads will end.
For a class that implements the Runnable interface, creating a thread object does not create a new execution thread, and similarly, calling its run () method does not create a new thread of execution. A new execution thread is created only when it is called by the start () method.
Writing a class and inheriting the thread class, overwriting the run () method in this class, and then creating an object of that class, and invoking the start () method, also creates an execution thread, as an example:
package concurrency;public class test2 extends thread { Private int number; public test2 (Int number) { this.number = number; } public static void main (String[] args) { for (int i = 1; i <= 10; i++) { test2 thread = new test2 (i); thread.start (); } } @Override public void run () { for (int i = 1; i <= 10; i+ +) { system.out.printf ("%s: %d * %d = %d\n ", thread.currentthread (). GetName (), Number,i,i*number ); } }}
Creation and operation of threads