Java實現多線程有兩種途徑:繼承Thread類和實現Runnable接口。
示例代碼如下:
public class MyThread extends Thread {
@Override
public void run() {
// 線程的任務
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
示例代碼如下:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 線程的任務
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
區別: