在Java中線程是Thread類的實例,有兩個方式可以開新線程,分別對應Thread的兩種構造方法:Thread()和Thread(Runnable target)。
實現Runnable接口
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
繼承Thread類
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
這兩種方法的關鍵就在於run()方法,新開的線程中要運行的代碼就寫在run()方法裏面,如果有很多方法,就要全部在run()裏面調用。