This article has shared with you the method of starting a Java thread 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 "); } } 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 "); } } 3. Use 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(); } 4. Comparison:
Advantages of implementing Runnable interface:
1) Suitable for multiple threads with 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 shared by multiple threads, and the code and data are independent.
Inheriting the advantages of Thread class:
1) You can abstract the thread class when you need to use abstract factory pattern design.
2) Multi-threaded synchronization
Advantages of using function bodies
1) There is no need to inherit thread or implement Runnable to narrow the scope.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.