继承Thread类
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
}
}
实现Callable接口并通过FutureTask包装器
class MyCallable implements Callable
{ public Integer call() {
// 线程执行的代码,返回计算结果
return 0;
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask
futureTask = new FutureTask<>(myCallable); Thread thread = new Thread(futureTask);
thread.start();
Integer result = futureTask.get(); // 获取计算结果
}
}
使用ExecutorService, Callable, Future
ExecutorService executor = Executors.newFixedThreadPool(2);
Future
future = executor.submit(new MyCallable()); // 可以在这里做其他事情
Integer result = future.get(); // 获取计算结果
executor.shutdown();
以上方法都可以用于实现多线程计算,但使用`ExecutorService`的方法更加灵活和高效,特别是当你需要管理多个线程时。使用`ExecutorService`可以控制线程池的大小,复用线程,以及优雅地关闭线程池。
请根据你的具体需求选择合适的方法来实现多线程计算