创建线程的多种方式

1. 继承 Thread 类:

        继承 Thread 类,重写 run 方法:

class MyThread01 extends Thread {
    @Override
    public void run() {
        super.run();
    }
}
public class Test01 {
    public static void main(String[] args) {
        MyThread01 t1 = new MyThread01();
        t1.start();
    }
}

2. 实现 Runnable 接口:

        实现 Runnable 接口,重写 run 方法,其思路是解耦合,将线程和线程要干的活分开

class MyRunnable implements Runnable{
    @Override
    public void run() {
        // 要执行的任务
    }
}
public class Test02 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t2 = new Thread(myRunnable);
        t2.start();
    }
}

3. 实现 Callable 接口:

         实现 Callable 借楼,重写 call() 方法。

        Callable 接口是 Java 中的一个泛型接口,用于定义一个可以返回结果并可能抛出异常的任务。Callable 接口的 call() 方法可以返回一个结果,并且可以抛出异常。Callable 接口的实现类需要实现 call() 方法,该方法在执行时会返回一个 Future 对象,通过该对象可以获取到计算结果 。

class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        // 要执行的任务
        return 0;
    }
}

public class Test03 {
    public static void main(String[] args) {
        MyCallable myCallable = new MyCallable();
        //FutureTask的原理可以简单描述为:
        // 它接受一个Callable或Runnable对象作为参数,
        // 在执行器线程中执行该对象,并返回一个Future对象,
        // 通过该对象可以获取到计算结果。
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        Thread t3 = new MyThread01();
        t3.start();
    }
}

4. 使用线程池:

public class Test04 {
    public static void main(String[] args) {
        // 先创建线程池,包含五个线程
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                // 执行的任务
            }
        });
        // 执行完毕关闭线程池
        executorService.shutdown();
    }
}

5. 使用匿名类:

public class Test05 {
    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                // 要执行的任务
            }
        }.start();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@糊糊涂涂

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

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

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

打赏作者

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

抵扣说明:

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

余额充值