One. Overview
There are two ways to create a thread, but in essence there is only one.
[1] inherits the thread, overriding the run () method.
[2] Implement the Runnable interface, overriding the run () method.
We can actually implement the Runnable method as a strategy model.
Two. Inheriting thread creating threads
@Test Public void Test () { new Thread () { publicvoid run () { for (;;) System. out. println ("running .... ") " ); }; }. Start (); }
Three. Implementing the Runnable Interface
@Test Public void test2 () { new Thread (new Runnable () { @Override public void run () { for(;;) System. out. println (""); } }). Start (); }
Four. Compare
The only way a thread is created is to create a thread object and then start the thread, otherwise the new state's thread is actually not a real thread.
So, what about the Runnable interface?
The run () method is just a thread logical unit.
We can understand that as a strategy pattern application, we create threads that are executing unused algorithms (policies).
Note: The start of a thread requires the invocation of JNI code, which means that the JVM is assigned a thread resource before it can be counted as a thread.
002 Creation of Threads