There are two ways in which Java creates threads
1. Implementation via Runnable interface (recommended method)
(1) Create a new class to implement the Runnable interface, you need to override the Run method
1 class Implements runnable{23 @Override4public void run () {56 }7 8 }
(2) Create a new thread object, passing in the constructor the class that implements the Runnable interface
New Thread (new myrunnable);
(3) Call the Start method of the thread
Thread.Start ();
2. Implement by inheriting the thread class
(1) Create a new class to inherit the thread class, you need to override the Run method
1 class extends thread{2 @Override3public void run () { 4 Super. Run (); 5 6 }7 }
(2) call the Start method of the thread class.
New MyThread (); Thread.Start ();
3. Example
Packagethread; Public classmultithread { Public Static voidMain (string[] args) {//1. The first method of creating a thread, using an interface to create a class that implements the interfaceRunnable Runnable =Newmyrunnable (); Thread Thread=NewThread (runnable); Thread.Start (); //2. The second method of creating threads, using thread to open threads but not recommendedMyThread thread2 =NewMyThread (); Thread2.start (); }}classMyrunnableImplementsrunnable{@Override Public voidrun () { for(inti = 0; i< 10; i++){ Try{System.out.println ("Use Runnable to open threads:" +i); Thread.Sleep (1000); } Catch(Interruptedexception e) {}}} }classMyThreadextendsthread{@Override Public voidrun () {Super. Run (); for(inti = 0; I < 10; i++) { Try{System.out.println ("Use thread to open threads:" +i); Thread.Sleep (1000); } Catch(Interruptedexception e) {} }}}
The results of the operation are as follows:
How Java threads are created