【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多线程编程。

猜你喜欢

转载自blog.csdn.net/u013675821/article/details/141107510