I. Overview
There are two ways to create threads in Java,
[1] Inheriting thread, overriding the Run () method
[2] Implementation of the Runnable interface, the implementation of the run () method.
The advanced interface in Juc is actually done in either of these ways.
Two. Inherit thread to create threads.
Public classCreateThread { Public Static voidMain (string[] args) {//Create a thread and complete the task one NewThread () {@Override Public voidrun () {Task1 (); }}.start (); NewThread () {@Override Public voidrun () {task2 (); }; }.start (); } Public Static voidTask1 () { for(intI=0;i< -; i++) { Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task1===>"+i); } } Public Static voidTask2 () { for(intI=0;i< -; i++) { Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task2===>"+i); } }}
Three. Implement the Runnable interface to create threads
Public classuserunnable { Public Static voidMain (string[] args) {NewThread (NewRunnable () { Public voidrun () {Task1 (); }}). Start (); NewThread (NewRunnable () { Public voidrun () {task2 (); }}). Start (); } Public Static voidTask1 () { for(intI=0;i< -; i++) { Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task1===>"+i); } } Public Static voidTask2 () { for(intI=0;i< -; i++) { Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System. out. println ("task2===>"+i); } }}
Four. Policy mode
In fact, there is only one way to create a thread, which is to create a thread object.
So what is the way we use the Runnable interface?
This is the use of a strategy model.
001 Creating and starting a thread