【Java 】常见的几种线程创建方式

在Java中,创建线程有几种常见的方式。以下是详细讲解这些方式:

1. 继承Thread类

通过继承Thread类并重写run方法来创建线程。

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread is running");
    }

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

2. 实现Runnable接口

通过实现Runnable接口并重写run方法来创建线程。

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread is running");
    }

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

3. 使用匿名内部类

通过匿名内部类实现Runnable接口来创建线程。

public class AnonymousRunnableExample {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread is running");
            }
        });
        thread.start(); // 启动线程
    }
}

4. 使用Lambda表达式

从Java 8开始,可以使用Lambda表达式来创建线程。

public class LambdaRunnableExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running");
        });
        thread.start(); // 启动线程
    }
}

5. 使用Callable接口和Future

Callable接口与Runnable接口类似,但它可以返回结果,并且可以抛出受检异常。Callable通常与ExecutorService一起使用。

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

public class CallableExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<Integer> callable = () -> {
            System.out.println("Thread is running");
            return 123;
        };

        Future<Integer> future = executorService.submit(callable);

        try {
            Integer result = future.get(); // 获取结果
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        executorService.shutdown();
    }
}

6. 使用线程池

线程池是一种管理线程的机制,可以重用线程,减少创建和销毁线程的开销。

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

public class ExecutorServiceExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Runnable task = () -> {
            System.out.println("Thread is running");
        };

        executorService.submit(task);
        executorService.submit(task);

        executorService.shutdown();
    }
}

总结

  • 继承Thread类:适用于需要扩展Thread类功能的情况。
  • 实现Runnable接口:适用于需要实现多个接口的情况。
  • 匿名内部类:适用于简单的任务,不需要创建单独的类。
  • Lambda表达式:适用于简单的任务,代码更加简洁。
  • Callable接口和Future:适用于需要返回结果的任务。
  • 线程池:适用于需要管理和重用线程的情况。

通过这些方式,可以灵活地创建和管理线程,以满足不同的需求。希望这些示例和解释能帮助你更好地理解和使用Java多线程编程。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值