Java实现多线程的方法有以下几种:
public class MyThread extends Thread {
public void run() {
// 线程的执行逻辑
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
public 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(); // 启动线程
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<Integer> {
public Integer call() {
// 线程的执行逻辑,返回一个结果
return 1;
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callable);
int result = future.get(); // 获取任务的返回结果
System.out.println(result);
executorService.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyRunnable implements Runnable {
public void run() {
// 线程的执行逻辑
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池
executorService.execute(new MyRunnable()); // 提交任务
executorService.shutdown(); // 关闭线程池
}
}