Java创建线程的几种方式

  • Post author:
  • Post category: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中几种常见的创建线程的方式。每种方式都有其适用的场景,可以根据实际需求选择合适的方式来创建线程。



版权声明:本文为qq_39939541原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。