Java創建多線程的方式有以下幾種:
class MyThread extends Thread {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyRunnable implements Runnable {
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() {
public void run() {
// 線程執行的代碼
}
});
thread.start();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
Runnable task = new Runnable() {
public void run() {
// 線程執行的代碼
}
};
executor.execute(task);
executor.shutdown();
}
}
以上都是Java中創建多線程的常用方式,選擇哪種方式取決于具體的需求和場景。