/**
* <p>Title: 實現Runnable接口,獲得線程。</p>
* <p>Description: 通過實現Runnable接口來獲得自己的線程(t2)。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: twothread.java</p>
* @version 1.0
*/
public class twothread implements Runnable {
/**
*<br>方法說明:構造器。實際線程,並啟動這個線程。
*<br>輸入參數:
*<br>返回類型:
*/
twothread() {
//獲取當前的線程
Thread t1 =Thread.currentThread();
t1.setName("The first main thread");
System.out.println("The running thread:" + t1);
//通過將本類(Runnable接口)和名稱構造一個線程
Thread t2 = new Thread(this,"the second thread");
System.out.println("creat another thread");
//啟動線程
t2.start();
try {
System.out.println("first thread will sleep");
Thread.sleep(3000);
}catch (InterruptedException e) {
System.out.println("first thread has wrong");
}
System.out.println("first thread exit");
}
/**
*<br>方法說明:線程主體。實現run方法。
*<br>輸入參數:
*<br>返回類型:
*/
public void run() {
try {
for (int i=0;i<5;i++) {
System.out.println("Sleep time for thread 2:"+i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("thread has wrong");
}
System.out.println("second thread exit");
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String args[]) {
new twothread();
}
}