java多线程创建方式

c209e0fa462041e38813fe5be4993b46.gif
1. 继承Thread类
这种方式是通过创建一个新的类继承自Thread类,并覆盖run()方法来创建线程。然后通过创建这个类的对象并调用其start()方法来启动线程。
public class MyThread extends Thread {
    public void run() {
        // 在这里定义线程的执行逻辑
    }

 

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 启动线程
    }
}

2. 实现Runnable接口
这种方式是通过创建一个实现了Runnable接口的类,并实现run()方法来创建线程。然后将这个类的对象作为参数传递给Thread类的构造器,并调用Thread对象的start()方法来启动线程。
public class MyRunnable implements Runnable {
    public void run() {
        // 在这里定义线程的执行逻辑
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start(); // 启动线程
    }
}

这种方式的优点在于,由于Java不支持多重继承,如果你的类需要继承其他类,那么实现Runnable接口将是唯一的选择。同时,这也使得你的线程类更加灵活,可以被设计成实现多个接口。
3. 实现Callable接口
这种方式是通过创建一个实现了Callable接口的类,实现call()方法,并使用FutureTask或者ExecutorService来创建线程。这种方式可以让你的线程带返回值。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableExample implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("Callable task is running on another thread");
        return "Callable result";
    }

    public static void main(String[] args) {
        CallableExample callableExample = new CallableExample();
        FutureTask<String> futureTask = new FutureTask<>(callableExample);

        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

这种方式允许你在call()方法中返回一个值,并且可以通过FutureTask的get()方法获取这个值。
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值