Call the thread’s run() method directly

public class TestStart { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(){ @Override public void run() { System.out.println("Thread t1 is working..." +System.currentTimeMillis()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }}}; t1.run(); Thread.sleep(2000); System.out.println("Thread Main is doing other thing..." +System.currentTimeMillis()); }}Copy the code

You can see that the main thread does not resume running until three seconds after t1.run(). That is, calling the thread’s run() method directly from the main method does not start a thread to execute the contents of the run() method, but rather synchronously.

2. Call the thread’s start() method

public class TestStart { public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(){ @Override public void run() { System.out.println("Thread t1 is working..." +System.currentTimeMillis()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }}}; t1.start(); Thread.sleep(2000); System.out.println("Thread Main is doing other thing..." +System.currentTimeMillis()); }}Copy the code

You can see at the end of the executiont1.start()After this row,The main thread continues immediatelyTo output the content after sleeping for 2s. In other words, t1 thread and main thread areAsynchronous executionAfter the start() method on thread T1 completes, the main thread continues to execute.There is no need to wait for the contents of the run() method body to complete.

3, summarize

1. To start a thread, you must use the start() method. Calling run() directly does not create a thread.

2. If you create a thread by passing in a Runnable object, the thread executes the Runnable object’s run() method; Otherwise, execute your own run() method.

3. Either implementing the Runnable interface or inheriting Thread objects, you can override the run() method to perform a given task.