在Java中,有兩種常見(jiàn)的方法來(lái)創(chuàng)建多線程:
class MyThread extends Thread {
public void run() {
// 線程要執(zhí)行的任務(wù)
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 啟動(dòng)線程
}
}
class MyRunnable implements Runnable {
public void run() {
// 線程要執(zhí)行的任務(wù)
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 啟動(dòng)線程
}
}
這兩種方法都可以實(shí)現(xiàn)多線程,但通常推薦使用實(shí)現(xiàn)Runnable接口的方式,因?yàn)镴ava只支持單繼承,通過(guò)實(shí)現(xiàn)接口的方式可以避免類(lèi)繼承的限制。此外,實(shí)現(xiàn)Runnable接口的方式還可以更好地實(shí)現(xiàn)代碼的解耦和復(fù)用。