创建线程的的方式
1、继承Thread类,重写run方法,实现方式简单,无法继承其他类,类只能单继承
2、实现Runable接口,重写run方法,相比继承Thread类的创建方式,避免了单继承的缺陷
3、实现Callable接口重写call方法,相比实现Runable接口的方式,Callable实现方式可以获取线程执行结果的返回值、以及抛出异常
4、线程池创建
public class ThreadTest{
// todo 这个一个继承Thread类的线程类
static class Thread1 extends Thread{
@Override
public void run(){
System.out.println("这个一个继承Thread类的线程");
}
}
// todo 实现Runnable接口的线程类
static class ThreadRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("这个一个实现 Runnable 接口的线程=="+i);
}
}
}
// todo 实现Callable接口的线程类
static class ThreadCallable implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 1000; i++) {
System.out.println("这个一个实现 Callable 接口的线程=="+i);
}
return "ss";
}
}
public static void main(String[] args) throws Exception {
// todo 继承类线程实现
new Thread().start();
// 启动callable接口线程
ThreadCallable threadCallable = new ThreadCallable();
FutureTask<String> ft = new FutureTask<>(threadCallable);
new Thread(ft).start();
// 打印返回结果
System.out.println(ft.get());
// todo 实现Runnable接口线程启动
ThreadRunnable threadRunnable = new ThreadRunnable();
new Thread(threadRunnable).start();
// 线程池创建
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(() -> {
for (int i = 0; i < 1000; i++) {
System.out.println("这个一个线程池创建的线程=="+i);
}
});
// 线程池关闭
executor.shutdown();
}
}
6种创建线程池的区别待完善
FixedThreadPool 定长线程池 | 核心线程数与最大线程数相同, 只有核心线程,线程数量固定,执行完立即回收,任务队列为链表结构的有界队列 |
SingleThreadExecutor 单线程化线程池 | 一个线程的线程池 |
CachedThreadPool 可缓存线程池 | 核心线程为0,最大线程数为Integer. MAX_VALUE, 无核心线程,非核心线程数量无限,执行完闲置 60s 后回收, 任务队列为不存储元素的阻塞队列 |
ScheduledThreadPool 定时线程池 | 指定核心线程数的定时线程池,核心线程数量固定,非核心线程数量无限,执行完闲置 10ms 后回收,任务队列为延时阻塞队列 |
SingleThreadScheduledExecutor | 单例的定时线程池 |
ForkJoinPool | JDK 7 新加入的一种线程池 |