在Java中实现多线程主要有以下几种方式:
继承Thread类
创建一个继承自`Thread`类的子类,并重写`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();
}
}
实现Runnable接口
创建一个实现了`Runnable`接口的类,并实现`run`方法,然后通过创建`Thread`对象并将其作为参数传递,接着调用`start`方法启动线程。
```java
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
实现Callable接口
创建一个实现了`Callable`接口的类,并实现`call`方法,然后通过`ExecutorService`提交任务,并通过`Future`获取返回值。
```java
class MyCallable implements Callable
public Integer call() {
// 线程执行的代码,返回一个整数
return 0;
}
}
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future
Integer result = future.get(); // 获取返回值
executor.shutdown();
}
}
使用线程池
使用`ExecutorService`创建线程池,提交任务,并通过`Future`获取返回值。
```java
ExecutorService executor = Executors.newFixedThreadPool(5);
Future
future = executor.submit(new MyCallable()); Integer result = future.get(); // 获取返回值
executor.shutdown();
以上是Java中实现多线程的主要方法。选择哪种方法取决于具体的应用场景和需求。需要注意的是,如果类已经继承了其他类,则不能继承`Thread`类,但可以实现`Runnable`接口