在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<Integer> { public Integer call() throws Exception { // 线程执行的代码,返回结果 return 42; } } public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Integer> future = executorService.submit(new MyCallable()); Integer result = future.get(); // 获取任务执行的结果 executorService.shutdown(); } }
import java.util.concurrent.CompletableFuture; import java.util.function.Function; @FunctionalInterface interface MyFunction { int apply(int input); } public class Main { public static void main(String[] args) { MyFunction myFunction = x -> x * 2; CompletableFuture<Integer> future = CompletableFuture.supplyAsync(myFunction, 42); future.thenAccept(result -> System.out.println("Result: " + result)); // 获取任务执行的结果 } }
这些方法都可以用于实现多线程,但它们之间有一些差异。继承Thread类和使用Runnable接口的方法较简单,但可能导致类继承层次结构复杂。而使用Callable接口和Future或CompletableFuture的方法更灵活,可以更好地控制任务的执行和结果处理。