在Java中,实现多线程主要有以下几种方法:
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyRunnable implements Runnable {
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.*;
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 线程执行的代码
return "任务结果";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(new MyCallable());
String result = future.get(); // 获取任务执行的结果
executorService.shutdown();
}
}
例如,使用线程池:
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
executorService.submit(() -> {
// 线程执行的代码
System.out.println("任务 " + taskNumber + " 正在执行");
});
}
executorService.shutdown();
}
}
这些方法都可以实现多线程,具体选择哪种方法取决于你的需求和场景。