One, the basic concept of threading
each run of a standalone program becomes a process.
Each process can also contain multiple subtasks that execute concurrently, corresponding to multiple threads.
Decomposing a process into multiple threads that do not affect each other can cause multiple threads to execute in parallel, greatly shortening the execution time.
two, implementing a new thread by inheriting the thread class
public class Factorialthreadtester {/** * main thread */public static void Main (string[] args) {System.out.println ("main thread St Arts "); Factorialthread thread=new factorialthread (); Thread.Start (); Open new Thread System.out.println ("main thread Ends");}} /* * New class inherits Thread, implement Run method * */class Factorialthread extends thread{private int num;public factorialthread (int num) {This.num =num;} @Overridepublic void Run () {int i=num;int result=-1; SYSTEM.OUT.PRINTLN ("New thread Started"), while (i>0) {result=result*i;i=i-1;} System.out.println ("The factorial of" +num+ "is :" +result); SYSTEM.OUT.PRINTLN ("New Thread Ends");}}
Results:
third, multithreading is realized by implementing Runnable interface
public class Implementrunnabledemo {public static void main (string[] args) {System.out.println ("main thread starts"); Facorialthread f=new Facorialthread, new Thread (f). Start ();//Open new Thread System.out.println ("New Thread Started,main Thread ends ");}} /* * * Implement Multi-threading through the implementation of the Runnable interface, implement the interface in the Run method * */class Facorialthread implements runnable{private int num;public facorialth Read (int num) {this.num=num;} @Overridepublic void Run () {int i=num;int result=-1; SYSTEM.OUT.PRINTLN ("New thread Started"), while (i>0) {result=result*i;i=i-1;} System.out.println ("The factorial of" +num+ "is :" +result); SYSTEM.OUT.PRINTLN ("New Thread Ends");}}
This method is not much different from inheriting the thread class, except that because Java is a single-inheritance language, the class that can implement multithreading has inherited other parent classes, and at the time, it is possible to implement multithreading in a way that implements interfaces.
As can be seen from the execution results, when the new thread is opened, the main thread continues execution, which means that the execution of the program is not blocked in the new thread's Start method.
Therefore, in performing time-consuming operations, such as network operations, IO reads, etc., we can re-open a thread and put in the new thread what we want to do to ensure that our other operations are unaffected.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java--thread/runnable Implementing multithreading