1.在java中,創建線程一般只有兩種方法;1)繼承Thread;2)實現Runnable接口;
2.繼承Thread類:
class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name = name;
}
//繼承Thread類的話,必須重寫run方法,在run方法中定義需要執行的任務
@Override
public void run() {
System.out.println("name:"+name+" 子線程ID:"+Thread.currentThread().getId());
}
}
public class test {
public static void main(String[] args) {
MyThread thread1 = new MyThread("thread1");
thread1.start();
}
}
3.注意點run和start使用誤區:
(1)線程啓動要用start()方法,只有它才能創建一個新的線程來執行定義的任務。
(2)run方法只是定義了需要執行的任務,如果調用run方法,即相當於在主線程中執行run方法,跟普通的方法調用沒有任何區別。
4.結果對比:
public class test {
public static void main(String[] args) {
System.out.println("主線程ID:"+Thread.currentThread().getId());
MyThread thread = new MyThread("thread");
thread.start();
thread.run();
MyThread thread2 = new MyThread("thread2");
thread2.run();
}
}
結論:1)調用了run()方法的子線程id與主線程id一致;不會創建新的線程,與普通方法調用一致。
2)調用了start()方法創建了新的線程。
5.實現Runnable接口:
public class Test {
public static void main(String[] args) {
System.out.println("主線程ID:"+Thread.currentThread().getId());
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
class MyRunnable implements Runnable{
public MyRunnable() {
}
@Override
public void run() {
System.out.println("子線程ID:"+Thread.currentThread().getId());
}
}
發現:1)這種方式必須將Runnable作爲Thread類的參數,然後通過Thread的start方法來創建一個新線程來執行該子任務。
2)源代碼中,Thread類是實現了Runnable接口方法的。
6.Thread與Runnable區別: