文章目录
- 1. 继承Thread类
 - 2. 实现Runnable接口
 - 3. 实现Callable接口
 - 4. 使用Executor框架
 - 4. 四者的区别
 
本人今年参加了很多面试,也有幸拿到了一些大厂的offer,整理了众多面试资料,后续还会分享众多面试资料。
整理成了面试系列,由于时间有限,每天整理一点,后续会陆续分享出来,感兴趣的朋友可关注+收藏
1. 继承Thread类
1.class MyThread extends Thread {
2.    public void run() {
3.        // 线程的执行逻辑
4.    }
5.}
6.public class Main {
7.    public static void main(String[] args) {
8.        MyThread thread = new MyThread();
9.        thread.start(); // 启动线程
10.    }
11.}
 
2. 实现Runnable接口
1.class MyRunnable implements Runnable {
2.    public void run() {
3.        // 线程的执行逻辑
4.    }
5.}
6.
7.public class Main {
8.    public static void main(String[] args) {
9.        MyRunnable myRunnable = new MyRunnable();
10.        Thread thread = new Thread(myRunnable);
11.        thread.start(); // 启动线程
12.    }
13.}
 
3. 实现Callable接口
1.public class MyThread implements Callable<String>{//Callable是一个泛型接口
2. @Override
3. public String call() throws Exception {//返回的类型就是传递过来的V类型
4. 		for(int i=0;i<10;i++){
5.   		System.out.println(Thread.currentThread().getName()+" : "+i);
6.  	}
7.  	return "Hello Tom";
8. }
9. public static void main(String[] args) throws Exception {
10.  	MyThread myThread=new MyThread();
11.  	FutureTask<String> futureTask=new FutureTask<>(myThread);
12.  	Thread t1=new Thread(futureTask,"线程1");
13.  	t1.start();
14.  	System.out.println(futureTask.get());
15. }
16.}
 
4. 使用Executor框架
1.import java.util.concurrent.Executor;
2.import java.util.concurrent.Executors;
3.public class Main {
4.    public static void main(String[] args) {
5.        Executor executor = Executors.newFixedThreadPool(2); // 创建线程池
6.        executor.execute(() -> {
7.            // 线程的执行逻辑
8.        });
9.    }
10.}
 
4. 四者的区别
1)实现Runnable/Callable接口相比继承Thread类的优势
 · 适合多个线程进行资源共享
 · 可以避免java中单继承的限制
 · 增加程序的健壮性,代码和数据独立
 · 线程池只能放入Runable或Callable接口实现类,不能直接放入继承Thread的类
2)Callable和Runnable的区别
 · Callable重写的是call()方法,Runnable重写的方法是run()方法
 · call()方法执行后可以有返回值,run()方法没有返回值
 · call()方法可以抛出异常,run()方法不可以
 · 运行Callable任务可以拿到一个Future对象,表示异步计算的结果 。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果
3)使用 Executor 框架更灵活,它可以更好地管理线程池、调度任务、控制线程生命周期等。这种方式通常更适合于大规模多线程应用。




![[ C++ ] STL---stack与queue](https://img-blog.csdnimg.cn/direct/7ce025ded1c14aa98e7f28d8dc41c42c.gif)














