Java啟動線程的方式有以下幾種:
public class MyThread extends Thread {
public void run() {
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
public void run() {
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
// 線程執(zhí)行的代碼
}
};
thread.start();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 線程執(zhí)行的代碼
});
thread.start();
}
}
這些方式都可以創(chuàng)建并啟動線程,但使用Runnable接口或Lambda表達式創(chuàng)建線程對象更為常見和靈活,因為Java不支持多重繼承,而實現Runnable接口可避免這個限制,并且可以在需要時重用實現了Runnable接口的對象。