Create a new class that can run threads in it. There are two ways: one is to expand the java. Lang. Thread class, and the other is to expand any class and implement the interface runnable.
(1) Extend java. Lang. Thread class
Public class twothread extends thread {// when a new thread is started,ProgramThe entry is the run () method. From the time the run () method was just called to the time the run () method was just returned, the new thread was considered to be alive. // After the run () method returns, the thread disappears and cannot be restarted after the thread dies. Public void run () {for (INT I = 0; I <2; I ++) {system. out. println ("New thread") ;}} public static void main (string [] ARGs) {twothread TT = new twothread (); // a running thread is created for the new thread, first, you must build a new thread instance. TT. Start (); // The twothread object calls the START () method to start thread execution. The START () method inherits from the thread // the newly created thread can start execution (enter the run method) at any time after the start () method is called. This means that, before executing any statements after the start () method, the original thread may be swapped out. For (INT I = 0; I <2; I ++) {system. Out. println ("main thread ");}}}
The output may be as follows: