返回
让java多线程更丝滑:5种创建线程的方式
后端
2023-09-10 12:07:38
1. Thread 类
Java 中最基本的方式,创建线程需要创建一个 Thread 类或实现 Runnable 接口,通常我们创建的是Thread
类,因为Runnable
需要一个Thread
对象来启动线程,既然这样,直接用Thread
对象会更简单。
线程类提供了一个run()方法,该方法定义了线程执行的任务。当您调用 start() 方法时,线程将开始执行该方法。
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2. Runnable 接口
Runnable 接口是一个函数式接口,只包含一个 run() 方法。您可以创建一个实现 Runnable 接口的类,并将其作为参数传递给 Thread 构造函数来创建线程。
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
3. Callable 接口
Callable 接口是一个泛型接口,可以返回一个值。您可以创建一个实现 Callable 接口的类,并将其作为参数传递给 ExecutorService 的 submit() 方法来创建线程。
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() {
// 线程执行的任务
return 42;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Integer> future = executorService.submit(new MyCallable());
Integer result = future.get();
System.out.println(result);
executorService.shutdown();
}
}
4. ExecutorService
ExecutorService 是一个并发框架的组件,它可以管理线程并执行任务。您可以使用 ExecutorService 来创建和管理线程池,以及提交任务给线程池执行。
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> {
// 线程执行的任务
});
executorService.shutdown();
}
}
5. Fork/Join 框架
Fork/Join 框架是一个并行编程框架,它允许您将任务分解成更小的任务,然后在多个线程上并行执行这些任务。
public class MyTask extends RecursiveTask<Integer> {
@Override
protected Integer compute() {
// 线程执行的任务
return 42;
}
}
public class Main {
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool();
MyTask task = new MyTask();
Integer result = forkJoinPool.invoke(task);
System.out.println(result);
}
}