java多线程的三种实现
时间: 2023-10-12 12:55:26 浏览: 40
Java中多线程的实现有三种方式:
1. 继承Thread类:创建一个继承自Thread类的子类,重写run()方法,在run()方法中定义线程要执行的任务。然后创建该子类的对象,并调用start()方法启动线程。
```java
class MyThread extends Thread {
public void run() {
// 线程要执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
```
2. 实现Runnable接口:创建一个实现了Runnable接口的类,实现run()方法,在run()方法中定义线程要执行的任务。然后创建该类的对象,并将其作为参数传递给Thread类的构造方法,最后调用start()方法启动线程。
```java
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();
}
}
```
3. 使用Callable和Future:创建一个实现了Callable接口的类,实现call()方法,在call()方法中定义线程要执行的任务,并返回一个结果。然后使用ExecutorService的submit()方法提交Callable任务,得到一个Future对象,通过调用Future对象的get()方法可以获取线程执行的结果。
```java
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();
MyCallable myCallable = new MyCallable();
Future<Integer> future = executorService.submit(myCallable);
Integer result = future.get();
System.out.println(result);
executorService.shutdown();
}
}
```
这三种方式都可以实现多线程,每种方式都有自己的优势和适用场景,选择合适的方式取决于具体的需求。