Java-三种线程的实现方式

1. 继承Thread类

可以通过创建一个新的类继承Thread类,并重写其run方法来实现线程。

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程运行中:" + Thread.currentThread().getName());
        // 线程要执行的代码
    }
}

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

2. 实现Runnable接口

更常见的方式是实现Runnable接口,因为它允许类继承其他类的同时实现多线程。这遵循了面向对象编程的最佳实践,即组合优于继承。

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程运行中:" + Thread.currentThread().getName());
        // 线程要执行的代码
    }
}

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

3. 实现Callable接口

Callable接口与Runnable类似,但它可以返回值并抛出异常。要使用Callable,通常需要结合FutureTask使用。

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

class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("Callable线程运行中:" + Thread.currentThread().getName());
        // 线程要执行的代码,并返回结果
        return 123;
    }
}

public class CallableExample {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start(); // 启动线程

        // 获取callable线程的执行结果
        Integer result = futureTask.get();
        System.out.println("Callable线程结果:" + result);
    }
}

在实际应用中,选择哪种方式来实现线程通常取决于具体需求。如果需要返回结果或抛出异常,那么Callable可能是更好的选择。如果不需要这些功能,Runnable通常是首选,因为它更简单,也更灵活。继承Thread类的方式现在较少使用,因为它限制了类的继承结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值