I. Overview
There are two ways to create a thread, but in fact there is only one way.
[1] Inherit Thread and override the run() method.
[2] Implement the Runnable interface and override the run() method.
We can actually implement the Runnable method as a strategy pattern implementation.
2. Inherit Thread to create a thread
@Test public void test() { new Thread() { public void run() { for(;;) System.out.println("running...."); }; }.start(); }
3. Implement the Runnable interface
@Test public void test2() { new Thread(new Runnable() { @Override public void run() { for(;;) System.out.println("running ... "); } }).start(); }
4. Comparison
In fact, there is only one way to create a thread, that is to create a Thread object and then start the thread, otherwise the thread in the new state is not actually a real thread.
So, what about the Runnable interface?
The run() method is just a thread logic unit.
We can understand it as an application of the strategy pattern, and the threads we create are executing different algorithms (strategies).
Note: The startup of a thread needs to call the JNI code, that is, after the JVM allocates thread resources, it can be regarded as a thread.