I. Overview
There are two ways to create threads in java,
[1] Inherit Thread and override the run() method
[2] Implement the Runnable interface and implement the run() method.
The high-level interface in JUC is actually completed in these two ways.
2. Inherit Thread to create a thread.
public class CreateThread { public static void main(String[] args) { // Create a thread and complete the task together new Thread() { @Override public void run() { task1(); } }.start(); new Thread() { @Override public void run() { task2(); }; }.start(); } public static void task1() { for(int i=0;i<20;i++) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("task1===>"+i); } } public static void task2() { for(int i=0;i<20;i++) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("task2===>"+i); } } }
3. Implement the Runnable interface to create threads
public class UseRunnable { public static void main(String[] args) { new Thread(new Runnable() { public void run() { task1(); } }).start(); new Thread(new Runnable() { public void run() { task2(); } }).start(); } public static void task1() { for(int i=0;i<20;i++) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("task1===>"+i); } } public static void task2() { for(int i=0;i<20;i++) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("task2===>"+i); } } }
4. Strategy Mode
In fact, there is only one way to create a thread, that is to create a Thread object.
So how do we use the Runnable interface?
This is the use of a strategy pattern.