Comparison and analysis of three ways to start a thread by java

  • 2020-05-26 09:15:56
  • OfStack

For your reference, this article shares the method of starting threads with java as an example. The details are as follows

1. Thread inheritance


public class java_thread extends Thread{ 
  public static void main(String args[]) 
  { 
    (new java_thread()).run(); 
    System.out.println("main thread run "); 
  } 
  public synchronized void run() 
  { 
    System.out.println("sub thread run "); 
  } 
 
} 

2. Implement Runnable interface


public class java_thread implements Runnable{ 
  public static void main(String args[]) 
  { 
    (new Thread(new java_thread())).start(); 
    System.out.println("main thread run "); 
  } 
  public void run() 
  { 
    System.out.println("sub thread run "); 
  } 
 
} 

3. Use directly in the body of a function


void java_thread() 
{ 
 
   Thread t = new Thread(new Runnable(){ 
      public void run(){ 
      mSoundPoolMap.put(index, mSoundPool.load(filePath, index)); 
      getThis().LoadMediaComplete(); 
      }}); 
    t.start(); 
} 

4. Compare:

Achieve Runnable interface advantages:
1) it is suitable for multiple threads of the same program code to process the same resource
2) you can avoid the limitation of single inheritance in Java
3) to increase the robustness of the program, the code can be Shared by multiple threads, and the code and data are independent.

Inherit Thread class advantages:
1) thread classes can be abstracted out when it is necessary to design using the abstract factory pattern.
2) multi-threading synchronization

Use the advantage in the body
1) narrow the scope without inheriting thread or implementing Runnable.


Related articles: