前言
多線程是我們開發過程中經常遇到的,也是必不可少需要掌握的。當我們知道需要進行多線程開發時首先需要知道的自然是如何實現多線程,也就是我們應該如何創建線程。
在Java中創建線程和創建普通的類的對象操作是一樣的,我們可以通過兩種方式來創建線程:
1、繼承Thread類,并重寫run()方法。
2、實現Runnable接口,并實現run()方法。
方法一:繼承Thread類
代碼非常簡單
首先重載一個構造函數,以便我們可以給線程命名。
重寫run()方法。
這里我們先讓線程輸出線程名+start。
然后每5ms輸出線程名+一個遞增數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * Created by holten.gao on 2016/10/17. */ public class threadThread extends Thread { public threadThread(String name) { super (name); } @Override public void run() { System.out.println( this .getName()+ " start!" ); for ( int i= 0 ;i< 10 ;i++){ System.out.println( this .getName()+ " " +i); try { Thread.sleep( 5 ); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
方法二:實現Runnable接口
代碼也非常簡單
實現run()方法。
這里我們先讓線程輸出線程名+start。
然后每5ms輸出線程名+一個遞增數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/** * Created by holten.gao on 2016/10/17. */ public class runnableThread implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()+ " start!" ); for ( int i= 0 ;i< 10 ;i++){ System.out.println(Thread.currentThread().getName()+ " " +i); try { Thread.sleep( 5 ); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
測試結果
測試代碼
1
2
3
4
5
6
7
8
9
10
11
|
/** * Created by holten.gao on 2016/10/17. */ public class Main { public static void main(String[] args) { Thread threadThread= new threadThread( "threadThread" ); threadThread.start(); Thread runnableThread= new Thread( new runnableThread(), "runnableThread" ); runnableThread.start(); } } |
測試結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
threadThread start! threadThread 0 runnableThread start! runnableThread 0 threadThread 1 runnableThread 1 threadThread 2 runnableThread 2 threadThread 3 runnableThread 3 threadThread 4 runnableThread 4 threadThread 5 runnableThread 5 threadThread 6 runnableThread 6 threadThread 7 runnableThread 7 threadThread 8 runnableThread 8 threadThread 9 runnableThread 9 |
兩種方法比較
1.因為Java只支持單繼承,所以使用方法一就不能再繼承其他類了;而方法二實現接口則不會影響繼承其他類。
2.方法一由于是繼承Thread,所以直接new出來就可以start;而方法二需要將對象作為參數傳入Thread對象才能得到Thread對象。
3.方法一中可以直接通過this.getName獲得線程名;而方法二需要Thread.currentThread().getName()獲得
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。