Home > Java > javaTutorial > body text

Comparative analysis of three ways to start threads in java

高洛峰
Release: 2017-01-21 16:33:41
Original
1308 people have browsed it

The example of this article shares the method of starting a thread in java for your reference. The specific content is as follows

1. Inherit Thread

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 ");
  }
  
}
Copy after login

2. Implement the 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 ");
  }
  
}
Copy after login

3. Use it directly in the function body

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

4. Compare:

Advantages of implementing the Runnable interface :
1) Suitable for multiple threads of the same program code to process the same resource
2) Can avoid the limitation of single inheritance in Java
3) Increase the robustness of the program, the code can be used by multiple Threads are shared and code and data are independent.

Advantages of inheriting the Thread class:
1) The thread class can be abstracted when it is necessary to use the abstract factory pattern design.
2) Multi-thread synchronization

Advantages of using function body
1) No need to inherit thread or implement Runnable to reduce the scope.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles on comparative analysis of the three ways to start threads in Java, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!