🕑 多线程的实现方式
<作者ssc>
## 1.继承Thread类
```java
//1.继承Thread类,重写run方法
public class Thread01 extends Thread{
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
//获取线程名字
System.out.println(getName()+"hello");
}
}
}
//2.创建对象,启动线程
@Test
public void test01(){
Thread01 t1 = new Thread01();
t1.setName("线程1");
t1.start();
}
```
`优点:使用非常简单。缺点:扩展性较差,因为java是单继承,不能再继承其它类。`
## 2.实现Runnable接口
```java
//1.实现Runnale接口,重写run方法
public class Thread02 implements Runnable{
public void run() {
for (int i = 0; i <100 ; i++) {
//获取当前线程,因为getName是Thread类的成员方法,只有继承了Thread类才能直接使用
Thread thread = Thread.currentThread();
//获取线程名字
System.out.println(thread.getName()+"hello");
}
}
}
//2.创建对象当参数使用构造方法创建Thread类的对象,启动线程
@Test
public void test02(){
Thread02 thread02 = new Thread02();
Thread t1 = new Thread(thread02);
t1.setName("线程1");
t1.start();
}
```
`优点:扩展性强,实现Runnable接口的同时还可以继承其它类来拓展功能。`
## 3.实现Callable接口
```java
//1.实现Callable接口泛型需要的返回类型,重写call方法
public class Thread03 implements Callable<Integer> {
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <100 ; i++) {
sum = sum+i;
}
return sum;
}
}
//2.创建对象,创建FutureTask对象管理线程运行结果,并当作参数用构造方法创建Thread对象,启动线程
@Test
public void test03() throws Exception {
Thread03 thread03 = new Thread03();
//创建FutureTask对象管理线程运行结果
FutureTask<Integer> futureTask = new FutureTask<Integer>(thread03);
Thread t1 = new Thread(futureTask);
t1.start();
int sum = futureTask.get();
System.out.println(sum);
}
```
`优点:可以获取线程执行的返回值,并且实现Callable接口的同时还可以继承其它类来拓展功能。`