Java多线程主要有以下几种实现方法:
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池
for (int i = 0; i < 10; i++) {
executorService.submit(new MyRunnable()); // 提交任务到线程池执行
}
executorService.shutdown(); // 关闭线程池
}
}