Way one: Inherit the Thread class.
/** The main function is also called the main function (also known as the main thread), * Because the execution of all the code starts here. */ Public Static voidMain (string[] args) {//in the test class, create the thread object. MyThread MT1 =NewMyThread (); //turn on the thread. //Start ()//Mt1.run (); //If you call the run () method, it is just a normal method call. Mt1.start ();//The open thread must call the start () method, which automatically calls the run () method. //Mt1.start (); //the same thread cannot be opened repeatedly, otherwise it will report: Illegalthreadstateexception exception. for(inti = 1; I <= 100; i++) {System.out.println ("Main ...." +i); } } /*** Custom Thread class: MyThread *@author * *///1) Define a class (MyThread) that inherits the thread class. Public classMyThreadextendsthread{//2) rewrite Thread#run ().@Override Public voidrun () {//3) Put the code you want to execute into the run () method. for(inti = 1; I <= 100; i++) {System.out.println ("run______________" +i); } }}
Mode two: Implement Runnable interface.
Public Static voidMain (string[] args) {//Formatting code: ALT + SHIFT + S --and letter F//in the test class, create a subclass object for the Runnable interface,Myrunnable Mr =Newmyrunnable (); //and passes it as a parameter to the construction of the thread class, creating a Threading object. Thread th =NewThread (MR); //turn on the thread.//Start ()Th.start (); for(inti = 1; I <= 100; i++) {System.out.println ("main***" +i); } } /*** The specific implementation class of the Runnable interface *@author * *///1) Define a class (myrunnable) to implement the Runnable interface. Public classMyrunnableImplementsRunnable {//2) rewrite Runnable#run ().@Override Public voidrun () {//3) Put the code you want to execute into the run () method. for(inti = 1; I <= 100; i++) {System.out.println ("run______________" +i); } }}
Method Three: Use with thread pooling (implement callable interface).
After the realization of-_,
Java-based multi-threading Two: Multithreading Implementation method