在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();
}
}
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// 代码逻辑
return 42;
}
}
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(new MyCallable());
Integer result = future.get(); // 获取任务执行结果
executorService.shutdown();
}
}
import java.util.concurrent.CompletableFuture;
class MyCompletableFuture {
public static CompletableFuture<Integer> compute() {
return CompletableFuture.supplyAsync(() -> {
// 代码逻辑
return 42;
});
}
}
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> future = MyCompletableFuture.compute();
future.thenAccept(result -> {
// 处理任务执行结果
});
}
}
这些是实现Java多线程的几种常见方式,可以根据具体需求选择合适的方法。