在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多線程的幾種常見方式,可以根據具體需求選擇合適的方法。