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中创建多线程的常用方式,选择哪种方式取决于具体的需求和场景。