四种多线程对比(异步)
创建和初始化多线程的几种方式
1、继承Thread
2、实现Runnable接口
3、实现Callable接口 + FutureTask(可以拿到返回结果,可以处理异常)
4、线程池
1、方式一:继承 Thread 类
public class ThreadTest {
public static void main(String
[] args
) {
System
.out
.println("main...start....");
Thread1 thread1
= new Thread1();
thread1
.start();
System
.out
.println("main...end....");
}
public static class Thread1 extends Thread {
@Override
public void run() {
System
.out
.println("当前线程:" + Thread
.currentThread().getId());
int i
= 10 / 2;
System
.out
.println("运行结果:" + i
);
}
}
}
2、方式二:实现 Runnable 接口
public class ThreadTest {
public static void main(String
[] args
) {
System
.out
.println("main...start....");
Runable01 runable01
= new Runable01();
new Thread(runable01
).start();
System
.out
.println("main...end....");
}
public static class Runable01 implements Runnable {
@Override
public void run() {
System
.out
.println("当前线程:" + Thread
.currentThread().getId());
int i
= 10 / 2;
System
.out
.println("运行结果:" + i
);
}
}
}
3、方式三:实现Callable接口 + FutureTask(可以拿到返回结果,可以处理异常)
public class ThreadTest {
public static void main(String
[] args
) {
System
.out
.println("main...start....");
FutureTask
<Integer> futureTask
= new FutureTask<>(new Callable01());
new Thread(futureTask
).start();
Integer integer
= futureTask
.get();
System
.out
.println("main...end...."+integer
);
}
public static class Callable01 implements Callable<Integer> {
@Override
public Integer
call() throws Exception
{
System
.out
.println("当前线程:" + Thread
.currentThread().getId());
int i
= 14 / 2;
System
.out
.println("运行结果:" + i
);
return i
;
}
}
}
4、线程池
我们以后的业务代码里,以上三种启动线程的方方式都不用
以上三种方式,其实就是一种方式,就是一直创建对象,如下代码
new Thread(()-> System
.out
.println("hello")).start();
总结:将所有的多线程异步任务都交给线程池执行
package com.ctra.gulimall.search.thread
;
import java.util.TreeMap
;
import java.util.concurrent.*
;
public class ThreadTest
{
// 创建全局线程池
public static ExecutorService
service = Executors.newFixedThreadPool
(10
);
public static void main
(String
[] args
) throws ExecutionException, InterruptedException
{
System.out.println
("main...start....");
// 4、线程池
// 整个系统一两个线程池,每个异步任务,提交给线程池让他自己去执行就行
service.execute
(new Runable01
());
System.out.println
("main...end....");
}
}
service(线程池) 中可以使用 submiit 和 execute 来存入线程,对比一个有返回值一个无返回值
5、开发中为什么使用写线程池