We can implement multithreading by inheriting class thread or implementing the Runnable interface. Thread has two of the most important functions run () and start ().
The run () function must be overwrite and put the code that will be processed in parallel in multiple threads into this function.
Although the run () function implements parallel processing for multiple threads, we cannot call the run () function directly, but instead start multithreading by calling the start () function.
When start () is called, the start () function starts with multithreading-related initialization, and the start () function invokes the run () function on its own.
If the developer calls the run () method directly, it will be executed as a normal serial program, rather than multithreaded.
Java source code for the implementation of simple multithreading
PackageCom.thread;/** * A simple java multithreading * * @author Fan Fangming */ Public class easythread extends Thread { inti =0, j =0, k=0;intFlag =0; Public void Run() {//Let the system run 6 times, in order to observe the results can be for(intCount =0; Count <6; Count + +) {Try{Thread.Sleep ( -); }Catch(Exception e) {E.printstacktrace (); }if(Flag = =0) {i++; System.out.println ("i="+ i); }Else if(Flag = =1) {j + +; System.out.println ("b Split point: j="+ j); }Else{k++; System.out.println ("C Split point: k="+ k); } } } Public Static void Main(string[] args) {Easythread Thread1 =NewEasythread (); Thread1.flag =0;//Do not call the Run method directly, otherwise it will be treated as a normal serial thread //thread1.run ();Thread1.start (); Easythread thread2 =NewEasythread (); Thread2.flag =1; Thread2.start (); Easythread thread3 =NewEasythread (); Thread3.flag =2; Thread3.start (); }}
Run Results
B Split point: J=1
I=1
C Split point: k=1
B Split point: j=2
C Split point: k=2
i=2
B Split point: j=3
I=3
C Split point: k=3
B Split point: j=4
C Split point: k=4
I=4
B Split point: j=5
C Split point: k=5
I=5
C Split point: k=6
B Split point: j=6
I=6
If we call the Run method directly, for example, the following is handled.
Thread1.run ();
Thread1.start ();
...
Run results
I=1
i=2
I=3
I=4
I=5
I=6
B Split point: J=1
C Split point: k=1
B Split point: j=2
C Split point: k=2
C Split point: k=3
B Split point: j=3
B Split point: j=4
C Split point: k=4
B Split point: j=5
C Split point: k=5
B Split point: j=6
C Split point: k=6
It is obvious that the first I-related thread is called as a normal method, followed by two, which is a multi-threaded operation.
A good memory is better than a bad pen. 73-multithreading-inheriting thread implements simple multithreading