Java创建线程的几种方式

一、继承Thread类

通过继承Thread类并重写run()方法来创建线程。然后,可以通过创建Thread对象并调用start()方法来启动线程。

class MyThread extends Thread {
    public void run() {
        // 线程执行的代码
    }
}

// 创建线程并启动
MyThread thread = new MyThread();
thread.start();

二、实现Runnable接口

通过实现Runnable接口来创建线程。需要实现Runnable接口中的run()方法。然后,可以创建Thread对象,将实现了Runnable接口的对象作为参数传递给Thread对象,并调用start()方法来启动线程。

class MyRunnable implements Runnable {
    public void run() {
        // 线程执行的代码
    }
}

// 创建线程并启动
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();

三、使用匿名类实现Runnable接口

可以通过使用匿名类实现Runnable接口来创建线程。这种方式可以简化代码,特别是对于一次性使用的线程。

Runnable runnable = new Runnable() {
    public void run() {
        // 线程执行的代码
    }
};

// 创建线程并启动
Thread thread = new Thread(runnable);
thread.start();

四、使用Callable和Future

Callable是一个带有返回值的线程,通过实现Callable接口并实现call()方法来创建线程。可以使用ExecutorService来提交Callable任务,并返回一个Future对象,通过调用Future对象的get()方法来获取线程的返回值。

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

class MyCallable implements Callable<Integer> {
    public Integer call() throws Exception {
        // 线程执行的代码
        return 42;
    }
}

// 创建ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();

// 提交Callable任务并获取Future对象
Future<Integer> future = executor.submit(new MyCallable());

// 获取线程的返回值
int result = future.get();

// 关闭ExecutorService
executor.shutdown();

以上是Java中几种常见的创建线程的方式。每种方式都有其适用的场景,可以根据实际需求选择合适的方式来创建线程。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Run,boy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值