How to write a threaded thread:
Way One:
1) Write a class that inherits the thread class, overriding the run () method
2) Create an object of this class, call Start ()
Code:
MyThread---> Provides a constructor method that invokes the constructor of the parent class in order to provide a name for the thread!
Package Cn.itcast.thread;public class MyThread extends Thread{private string name, public MyThread (string name) {// Pass the Ming Chen Super (name) to the thread by constructing the method; } @Overridepublic void Run () {for (int i=0;i<100;i++) {System.out.println (GetName () + ":" +i);}}}
Test class:
Package Cn.itcast.thread;public class Mythreadtest {public static void main (string[] args) {MyThread my1=new MyThread ("Li Wei Health "); MyThread my2=new MyThread ("Anlu"); My1.start (); My1.setname ("Wang Chao");///Set the name of the thread My2.start (); System.out.println (Thread.CurrentThread (). GetName ());}}
Way two:
1) Write a class to implement the Runable interface
2) Create a thread object to pass in the class you just wrote
3) Call the Start method
Code:
Myrunable
Package Cn.itcast.runable;public class Myrunable implements runnable{@Overridepublic void Run () {for (int i=0;i<10;i+ +) {System.out.println (Thread.CurrentThread (). GetName () + ":" +i);}}}
Myrunabletest
Package Cn.itcast.runable;public class Myrunabletest {public static void main (string[] args) {myrunable my=new myrunable ( ); Thread t1=new thread (my); T1.start ();}}
Explanation: What is the process of thread execution?
Interview questions:
What is the difference between the run method of the calling thread class and the Execute Start method?
Start: Starts the thread with the Start method, actually implements the multi-threaded operation, then executes the following code without waiting for the Run method body code to complete. By invoking the start () method of the thread class to start a thread, the thread is in a ready (operational) state and is not running, and once the SPU time slice is obtained, the run () method is executed, where the method run () is called the thread body, which contains the contents of the thread to be executed. This thread terminates when the Run method finishes running. The Run:run () method is just a common method of the class, if you call the Run method directly, the program is still only the main thread of the threads, its program execution path is only one, or to execute sequentially, or to wait for the Run method body to complete before you can continue to execute the following code, This will not achieve the purpose of writing threads. Summary: Call the Start method to start the thread, and the Run method is just a normal method call to thread, or execute in the main thread.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two ways to implement Java multithreading