1. Define the thread class that implements the Runnable interface, in the following steps:
(1) Create a thread class runner that implements the Runnable interface;
(2) rewrite the Run () method of the Runnable interface to define the running body of the thread; (Runnable interface has only one method)
(3) Instantiate thread class runner;
(4) Create the thread instance and pass the instance of the thread class runner to it as the parameter of the constructor function;
(5) Start thread;
The code looks like this:
1 Public classTestthread {2 Public Static voidMain (String args[]) {3Runner r =NewRunner ();//3. Instantiating thread classes runner4Thread thread =NewThread (R);//4. Create a thread instance and pass an instance of the thread class runner to it as a parameter to the constructor5Thread.Start ();//5. Start the thread6 7 for(inti=0; i<100; i++) {//main thread other code8System.out.println ("Main Thread:------" +i);9 }Ten } One } A - classRunnerImplementsRunnable {//1. Create a thread class that implements the Runnable interface runner - Public voidRun () {//2. Override the Run method to define the running body of the thread the for(inti=0; i<100; i++) { -System.out.println ("Runner1:" +i); - } - } +}
2. Define a subclass that inherits from the thread class and override its Run method
(1) Create subclass Mythread class that inherits from thread class;
(2) rewrite its Run method to define the thread's running body;
(3) Instantiation line Cheng Zi class mythread;
(4) Start thread;
1 Public classTestthread {2 Public Static voidMain (String args[]) {3MyThread MyThread =NewMyThread ();//3. Instantiate line Cheng Zi class mythread4Mythread.start ();//4. Start the thread5 6 for(inti=0; i<100; i++) {//main thread other code7System.out.println ("Main Thread:------" +i);8 }9 }Ten } One A classMyThreadextendsThread {//1. Create subclass Mythread class that inherits from the thread class - Public voidRun () {//2. Override its Run method to define the thread's runtime - for(inti=0; i<100; i++) { theSystem.out.println ("Runner1:" +i); - } - } -}
Note: It is recommended to create threads in a way that implements the Runnable interface, because it is relatively flexible to implement other interfaces and inherit other classes
Two ways to create threads in Java