本文實例為大家分享了java啟動線程的方法,供大家參考,具體內容如下
1.繼承Thread
1
2
3
4
5
6
7
8
9
10
11
12
|
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.實現Runnable接口
1
2
3
4
5
6
7
8
9
10
11
12
|
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.直接在函數體使用
1
2
3
4
5
6
7
8
9
10
|
void java_thread() { Thread t = new Thread( new Runnable(){ public void run(){ mSoundPoolMap.put(index, mSoundPool.load(filePath, index)); getThis().LoadMediaComplete(); }}); t.start(); } |
4.比較:
實現Runnable接口優勢:
1)適合多個相同的程序代碼的線程去處理同一個資源
2)可以避免Java中的單繼承的限制
3)增加程序的健壯性,代碼可以被多個線程共享,代碼和數據獨立。
繼承Thread類優勢:
1)可以將線程類抽象出來,當需要使用抽象工廠模式設計時。
2)多線程同步
在函數體使用優勢
1)無需繼承thread或者實現Runnable,縮小作用域。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。