Java创建线程的方式

  • Java创建线程的方式一共有三种:
    • 继承Thread类
    • 实现Runnable接口
    • 使用Executor框架
    • 使用Callable和Future接口
  • 其中,继承Thread类和实现Runnable接口都需要重写run()方法。

1. 继承Thread类

  • 继承Thread类是创建线程的最简单方式。通过继承Thread类并重写其run()方法来定义线程的任务。
1
2
3
4
5
6
7
8
9
10
11
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的逻辑
System.out.println("Thread is running");
}
}

// 创建并启动线程
MyThread thread = new MyThread();
thread.start();

2. 实现Runnable接口

  • 实现Runnable接口是另一种常用的创建线程的方式。通过实现Runnable接口并重写其run()方法来定义线程的任务。
1
2
3
4
5
6
7
8
9
10
11
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的逻辑
System.out.println("Runnable is running");
}
}

// 创建并启动线程
Thread thread = new Thread(new MyRunnable());
thread.start();

3. 使用Executor框架

  • 通过Executor可以将任务提交给线程池,由线程池来管理线程的生命周期和执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

class MyTask implements Runnable {
@Override
public void run() {
// 线程执行的逻辑
System.out.println("Task is running");
}
}

// 创建线程池
Executor executor = Executors.newFixedThreadPool(5);
// 提交任务给线程池
executor.execute(new MyTask());

4. 使用Callable和Future接口

  • 实现Callable接口可以创建可以返回结果的线程任务。与Runnable不同,Callable的call()方法可以返回一个值,并且可以抛出异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// 线程执行的逻辑
System.out.println("Callable is running");
return 42; // 返回结果
}
}

// 创建并启动线程
Future<Integer> future = Executors.newSingleThreadExecutor().submit(new MyCallable());
Integer result = future.get(); // 获取返回结果
System.out.println("Result: " + result);