Java创建线程的5种方式(附代码示例)
在Java中,创建线程有以下五种常见方式:
- 继承
Thread
类 - 实现
Runnable
接口 - 使用
Callable
和Future
- 使用线程池
- 使用
ForkJoinPool
(Java 7 引入)
以下是每种方式的示例代码:
- 继承
Thread
类:
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
// 使用
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
- 实现
Runnable
接口:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}
// 使用
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
- 使用
Callable
和Future
(通常与线程池结合使用):
import java.util.concurrent.*;
public class MyCallable implements Callable<String> {
public String call() throws Exception {
return "Callable is completed";
}
}
// 使用
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(myCallable);
System.out.println(future.get());
executorService.shutdown();
}
}
- 使用线程池:
import java.util.concurrent.*;
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}
// 使用
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(myRunnable);
executorService.shutdown();
}
}
- 使用
ForkJoinPool
:
import java.util.concurrent.*;
public class MyRecursiveTask extends RecursiveTask<Integer> {
private static final int THRESHOLD = 10000;
private int start;
private int end;
public MyRecursiveTask(int start, int end) {
this.start = start;
this.end = end;
}
protected Integer compute() {
int sum = 0;
if (end - start < THRESHOLD) {
for (int i = start; i < end; i++) {
sum
评论已关闭