多线程的创建和启动方式
在Java中,创建多线程主要有以下三种方式:
- 继承Thread类
- 实现Runnable接口
- 使用Callable接口与Future
下面是这三种方式的简单示例,以及如何在主类中启动它们。
1. 继承Thread类
class MyThread extends Thread {@Overridepublic void run() {System.out.println("Thread using inheritance from Thread class.");}
}
2. 实现Runnable接口
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("Thread using Runnable interface.");}
}
3. 使用Callable接口与Future
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {return "Thread using Callable interface.";}
}
主类用来启动线程
public class Main {public static void main(String[] args) {// 启动继承Thread类的线程MyThread thread1 = new MyThread();thread1.start();// 启动实现Runnable接口的线程Thread thread2 = new Thread(new MyRunnable());thread2.start();// 启动使用Callable接口的线程MyCallable myCallable = new MyCallable();FutureTask<String> futureTask = new FutureTask<>(myCallable);Thread thread3 = new Thread(futureTask);thread3.start();// 获取Callable线程的返回值try {String result = futureTask.get();System.out.println(result);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}
}
总结
- 使用
Thread
类时,创建一个子类,重写run
方法。 - 使用
Runnable
接口时,实现Runnable
接口,定义run
方法,再通过Thread
类启动。 - 使用
Callable
接口时,创建实现Callable
的类,使用FutureTask
来处理返回值,依然通过Thread
类启动。
这样,你就可以通过这三种方式创建和启动多线程了。