在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();
System.out.println("Result: " + result);
executorService.shutdown();
}
}
import java.util.concurrent.CompletableFuture;
@FunctionalInterface
interface MyFunction<T, R> {
R apply(T t);
}
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
// 代碼邏輯
return 42;
});
future.thenAccept(result -> {
System.out.println("Result: " + result);
});
}
}
這些方法都可以用于實現多線程,具體選擇哪種方法取決于你的需求和編程風格。