thread creation

There are several ways to write code that a thread executes when it runs:

  • Create an instance of the Thread subclass and override the run method
  • Create a class that implements the Runnable interface and pass it to the Thread class
  • lambda expression
  1. Create a subclass of Thread

     public class MyThread extends Thread {
         public void run() {
         	System.out.println("Hello new thread");
         }
     }
    

    A thread execution above can be created by:

     Mythread myThread = new MyThread();
     myThread.start();
    

    After the start() method is called, a new thread is started, the parent thread returns to continue execution, and the run() function defined above is executed in the child thread

  2. Implement the runnable interface

    Create a new instance object that implements the Runnable interface as the input parameter of the Thread class constructor:

     Runnable myRunnable = new Runnable() {
         public void run() {
     	    System.out.println("Hello Runnable");
         }
     }
     Thread thread = new Thread(myRunnable);
     thread.start();
    

    More commonly used is to start a thread directly using an anonymous inner class

     new Thread(new Runnable() {
         [@override](https://my.oschina.net/u/1162528)
         public void run() {
     	    System.out.println("Hello new thread");
         }
     }).start();
    
  3. After Java 1.8, you can use lambda expressions to simplify the operation

     new Thread( () -> System.our.println("Hello Lambda")).start();
    
  4. Use Executor to manage Thread objects

    Often a single Executor is used to create and manage all tasks in the system, and a call to the shutdown() method prevents new tasks from being submitted to this Executor.

     public class CachedThreadPool {
         public static void main(String[] args) {
     	    ExecutorService exec = Executors.newCachedThreadPool();
     	    for (int i = 0; i < 5; i++)
     		    exec.execute(new Runnable() {
     		    	  [@override](https://my.oschina.net/u/1162528)
     			    public void run() {
     			    System.out.println("")
     			}
     		};
     	exec.shutdown();
     }
    

    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325457167&siteId=291194637