創(chuàng)建一個線程,最簡單的方法是創(chuàng)建一個實現(xiàn)Runnable接口的類。
為了實現(xiàn)Runnable,一個類只需要執(zhí)行一個方法調(diào)用run(),聲明如下:
1
|
public void run() |
你可以重寫該方法,重要的是理解的run()可以調(diào)用其他方法,使用其他類,并聲明變量,就像主線程一樣。
在創(chuàng)建一個實現(xiàn)Runnable接口的類之后,你可以在類中實例化一個線程對象。
Thread定義了幾個構(gòu)造方法,下面的這個是我們經(jīng)常使用的:
1
|
Thread(Runnable threadOb,String threadName); |
這里,threadOb 是一個實現(xiàn)Runnable 接口的類的實例,并且 threadName指定新線程的名字。
新線程創(chuàng)建之后,你調(diào)用它的start()方法它才會運(yùn)行。
1
|
void start(); |
實例
下面是一個創(chuàng)建線程并開始讓它執(zhí)行的實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
// 創(chuàng)建一個新的線程 class NewThread implements Runnable { Thread t; NewThread() { // 創(chuàng)建第二個新線程 t = new Thread( this , "Demo Thread" ); System.out.println( "Child thread: " + t); t.start(); // 開始線程 } // 第二個線程入口 public void run() { try { for ( int i = 5 ; i > 0 ; i--) { System.out.println( "Child Thread: " + i); // 暫停線程 Thread.sleep( 50 ); } } catch (InterruptedException e) { System.out.println( "Child interrupted." ); } System.out.println( "Exiting child thread." ); } } public class ThreadDemo { public static void main(String args[]) { new NewThread(); // 創(chuàng)建一個新線程 try { for ( int i = 5 ; i > 0 ; i--) { System.out.println( "Main Thread: " + i); Thread.sleep( 100 ); } } catch (InterruptedException e) { System.out.println( "Main thread interrupted." ); } System.out.println( "Main thread exiting." ); } } |
編譯以上程序運(yùn)行結(jié)果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Child thread: Thread[Demo Thread, 5 ,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/duruiqi_fx/article/details/52187275