java八股文面试(一)线程创建方式

本文介绍了Java中创建线程的四种常见方法:继承Thread类、实现Runnable接口、使用Callable接口以及通过线程池。特别提到Java的单继承限制和接口多继承特性在这些方法中的应用。
摘要由CSDN通过智能技术生成

java创建线程有哪几种方式

我们熟悉的最多见的
一、继承Thread类
在这里插入图片描述
总结:这里重写的是run()方法,不是start()方法,因为java是单继承类,占用了继承的名额,后面如果在有需要继承的类,不方便扩展。
其实看底层源码会发现,Thread类也是实现了runnable,所以更加推荐使用第二种方式创建线程
在这里插入图片描述

二、实现Runnable接口
在这里插入图片描述
总结:这里用的还是Threa类,但是因为java可以多继承,后续在扩展方便,也是我们现在最常用的创建线程的方式。
拓展:
简化代码我们可以使用匿名内部类的方式编写

public class MuJieThread{
    public static void main(String[] args) {
        Thread thread=new Thread(new Runnable(){
            public void run(){
                System.out.println("Mujie Hello");
            }
        });
        thread.start();
    }
}

或者利用java8的新特性lambda表达式

public class MuJieThread{
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            System.out.println("MUjie Hello");
        });
        thread.start();
    }
}

三、实现Callable类

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class MuJieThread implements Callable<String> {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask=new FutureTask<>(new MuJieThread());
        Thread thread=new Thread(futureTask);
        thread.start();
        String result =futureTask.get();
        System.out.println(result);
    }

    @Override
    public String call() throws Exception {
        return "Mujie Hello";
    }
}

注意:这里不是实现run()方法,是call()方法,需要使用Thread+FutureTask配合,这种方式支持拿到异步执行任务的结果。
知识点:FutureTask的底层其实也是实现了Runnable类。
在这里插入图片描述
在这里插入图片描述
这里说一下,Java类是单继承,但是接口是可以多继承的。
四、利用线程池创建

import java.util.concurrent.*;

public class MuJieThread implements Runnable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService= Executors.newFixedThreadPool(10);
        executorService.execute(new MuJieThread());
    }

    @Override
    public void run() {
        System.out.println("Mujie Hello"); 
    }
}

这里实现Callable接口或者Runnable接口都可以。
其实上述四种方法都是围绕Runnable的。

总结:创建线程有四种方法,一、继承Thread类;二、实现Runnable接口;三、实现Callable接口;四、利用线程池创建
拓展:java类是单继承,接口可以多继承。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕孑晨

请大家多多支持,后续不断更新

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值