在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的方法更靈活,可以更好地控制任務的執行和結果處理。