大多數情況下, 通過實例化一個Thread對象來創建一個線程。Java定義了兩種方式:
- 實現Runnable接口。
- 可以繼承Tread類。
1. 實現Runnable接口
Runnable抽象了一個執行代碼單元,你可以通過實現Runnable接口的方法創建每一個對象的線程。爲實現Runnable接口,一個類僅需實現一個run()的簡單方法,該方法聲明如下:
public void run()
在run()中可以定義代碼來構建新的線程。run()方法能夠像主線程那樣調用其它方法, 引用其它類, 聲明變量。僅有的不同是run()在程序中確立另一個冼東妹的線程執行入口。當run()返回時,該線程結束。
創建了實現Runnable接口的類以後,你要在類內部實例化一個Thread類的對象。Thread類定義了好幾種構造函數,我們會用到的如下:
Thread(Runnable threadOb, String threadName)
建立新的線程後,它並不運行直到調用了它的方法start()方法,該方法在Thread類中定義。 本質上,start()執行的是一個對run()的調用。
例子:
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread( this, "Demo Thread" );
System.out.println( "Child thread : " + t );
t.start(); //Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for( int i = 5; i > 0; i-- ) {
System.out.println( "Child Thread : " + i );
Thread.sleep(500);
}
} catch ( InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println( "Exiting child thread." );
}
}
class ThreadDemo {
public static void main( String args[] ) {
new NewThread(); // create a new thread
try {
for ( int i = 5; i > 0; i-- ) {
System.out.println("Main Thread : " + i );
Thread.sleep(1000);
}
} catch ( InterruptedException e) {
System.out.println( "Main thread interrupted." );
}
System.out.println( "Main thread exiting." );
}
}
在NewThread構造函數中,新的Thread對象由下面的語句創建:
t = new Thread(this, "Demo Thread" );
通過前面的語句this表明在this對象中你想要新的線程調用run()方法。然後, start()被調用, 以run()方法爲開始啓動了線程的執行。
2. 擴展Thread
創建線程的另一個途徑是創建一個新類來擴展Thread類, 然後創建該類的實例。當一個類繼承Thread時, 它必須重載run()方法, 這個run()方法是新線程的入口。它也必須調用start()方法去啓動新線程的執行。下面用擴展Thread類重寫上面的例子:
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
supper ( "Demo Thread" );
System.out.println( "Child thread : " + this );
start(); // Start the thread
}
// Thhis is hte entry point for the second thread
public void run() {
try{
for ( int i = 5; i > 0; i-- ) {
System.out.println( "Child Thread : " + i );
Thread.sleep(500);
}
} catch ( InterruptedException e) {
System.out.println( " Child interrupted." );
}
System.out.println( " Exiting child thread." );
}
}
class ExtendThread {
public static void main( String args[] ) {
new NewThread(); // create a new thread.
try{
for ( int i = 5; i > 0; i-- ) {
System.out.println( "Main Thread : " + i );
Thread.sleep(1000);
}
} catch ( InterruptedException e ) {
System.out.println( "Main thread interrupted." );
}
System.out.println( " Main thread existing." );
}
}
注意NewThread中super()的調用, 該方法調用了下列形式的Thread構造函數:
public Thread(Sting threadName)
3. 選擇合適方法
Thread類定義了多種方法可以被派生類重載。 對於所有的方法, 唯一的必須被重載的是run()方法。這當然是實現Runnable接口所需的同樣的方法。很多程序員認爲類僅在它們被加強或修改時應該被擴展。因此, 如果你不重載Thread的其它方法時,最好只實現Runnable接口。