在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);
});
}
}
这些方法都可以用于实现多线程,具体选择哪种方法取决于你的需求和编程风格。