Java创建线程的四种方式

 1、继承Thread类

  1. 首先继承Thread类,然后重写run方法,run方法里面写线程的方法体

  2. 创建一个主线程,即main方法

  3. 在main方法中创建线程对象实例,调用start方法开启线程

注意:不要使用run()方法开启线程

public class MyThread extends Thread{
    //重写run方法
    @Override
    public void run() {
        System.out.println("继承Thread类创建线程");
    }

    public static void main(String[] args) {
        //创建继承Thread类的对象调用start方法来启动线程
        MyThread mythread = new MyThread ();
        MyThread .start();
    }
}

2、实现Runnable接口

  1. 首先实现Runnable接口

  2. 在main方法中创建一个实现该接口的对象并传进Thread类的匿名对象内

  3. 使用Thread类的匿名对象开启线程

优点:可避免单继承的局限性,方便一个对象被多个线程使用

public class MyThread implements Runnable{
    //重写run方法
    @Override
    public void run() {
        System.out.println("实现Runnable接口创建线程");
    }

    public static void main(String[] args) {
        //创建实现Runnable接口的类的对象
        MyThread mythread= new MyThread ();
        //使用Thread类的匿名对象调用start方法
        new Thread(mythread).start();
    }
}

3、实现Callable接口

  1. 实现Callable接口(需要定义返回值类型),重写call方法(需要抛出异常)

  2. 创建实现Callable接口的对象

  3. 创建执行服务,提交执行,获取结果

  4. 关闭服务

import java.util.concurrent.*;

public class MyThread implements Callable {
    //重写Callable接口
    @Override
    public String call() throws Exception {
        return "实现Callable接口创建线程";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建实现Callable接口的对象
        MyThread mythread = new MyThread ();
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(1);
        //提交执行
        Future<String> result = service.submit(mythread);
        //获取结果
        String serviceresult = result.get();
        //输出返回结果
        System.out.println(serviceresult);
        //关闭服务
        service.shutdownNow();
    }
}

4、创建线程池

  1. 创建线程池

  2. 调用execute方法并传入参数(Runnable或Thread接口对象)来启动线程

  3. 关闭服务

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThread{
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(1);
        //调用execute方法启动线程
        service.execute(()-> System.out.println("创建线程池启动线程"));
        //关闭服务
        service.shutdownNow();
    }
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只嘻嘻嘻

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值