Java中實現多線程的方法有以下幾種:
示例代碼:
public class MyThread extends Thread {
@Override
public void run() {
// 線程的任務
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
示例代碼:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 線程的任務
}
}
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(new Runnable() {
@Override
public void run() {
// 線程的任務
}
});
thread.start();
}
}
以上是Java中實現多線程的幾種常見方法,每種方法都有其適用的場景,開發者可以根據具體需求選擇合適的方法。