|
一、繼承Thread類 步驟: 1):定義一個(gè)類A繼承于Java.lang.Thread類. 2):在A類中覆蓋Thread類中的run方法. 3):我們在run方法中編寫需要執(zhí)行的操作:run方法里的代碼,線程執(zhí)行體. 4):在main方法(線程)中,創(chuàng)建線程對象,并啟動(dòng)線程: ? ? ? ? ? ? ? (1)創(chuàng)建線程類對象: ???????????????A類 ??a ?= ?new ??A類(); ? ? ? ? ? ? ? (2)調(diào)用線程對象的start方法: ???a.start();//啟動(dòng)一個(gè)線程 注意:千萬不要調(diào)用run方法,如果調(diào)用run方法好比是對象調(diào)用方法,依然還是只有一個(gè)線程,并沒有開啟新的線程. 線程只能啟動(dòng)一次! 創(chuàng)建啟動(dòng)線程實(shí)例: //1):定義一個(gè)類A繼承于java.lang.Thread類.
class MusicThread extends Thread{
private String idNum;
public MusicThread(String idNum) {
this.idNum= idNum;
}
//2):在A類中覆蓋Thread類中的run方法.
public void run() {
//3):在run方法中編寫需要執(zhí)行的操作
System.out.println(idNum);
}
}
public class ExtendsThreadDemo {
public static void main(String[] args) {
//4):在main方法(線程)中,創(chuàng)建線程對象,并啟動(dòng)線程.
MusicThread music = new MusicThread("123456");
music.start();
}
}
二、實(shí)現(xiàn)Runnable接口 步驟: 1):定義一個(gè)類A實(shí)現(xiàn)于java.lang.Runnable接口,注意A類不是線程類. 2):在A類中覆蓋Runnable接口中的run方法. 3):我們在run方法中編寫需要執(zhí)行的操作:run方法里的,線程執(zhí)行體. 4):在main方法(線程)中,創(chuàng)建線程對象,并啟動(dòng)線程: ?????(1)創(chuàng)建線程類對象:? ? ? ? Thread ?t = new Thread(new ?A()); ??? ?????(2)調(diào)用線程對象的start方法:? ? ?t.start(); 創(chuàng)建啟動(dòng)線程實(shí)例: //1):定義一個(gè)類A實(shí)現(xiàn)于java.lang.Runnable接口,注意A類不是線程類.
class MusicImplements implements Runnable{
private String idNum;
public void setId(String idNum){
this.idNum = idNum;
}
//2):在A類中覆蓋Runnable接口中的run方法.
public void run() {
//3):在run方法中編寫需要執(zhí)行的操作
System.out.println(idNum);
}
}
public class ImplementsRunnableDemo {
public static void main(String[] args) {
//4):在main方法(線程)中,創(chuàng)建線程對象,并啟動(dòng)線程
MusicImplements mi = new MusicImplements();
mi.setId("123456");
Thread t = new Thread(mi);
t.start();
}
}
繼承方式和實(shí)現(xiàn)方式的區(qū)別: 繼承方式: ? ? ? ? ? ? ? ? ? ? ? ? ??String name = Thread.currentThread().getName(); ?? ? ? ? ? ? ? 3):從多線程共享同一個(gè)資源上分析,實(shí)現(xiàn)方式可以做到(是否共享同一個(gè)資源). 來源:https://www./content-1-645651.html |
|
|