阅读量:0
Java实现多线程的方法有以下几种:
- 继承Thread类:创建一个继承自Thread类的子类,并重写run()方法,在run()方法中定义线程的执行逻辑。
public class MyThread extends Thread { public void run() { // 线程的执行逻辑 } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } }
- 实现Runnable接口:创建一个实现了Runnable接口的类,并实现run()方法,在run()方法中定义线程的执行逻辑。
public class MyRunnable implements Runnable { public void run() { // 线程的执行逻辑 } } public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); // 启动线程 } }
- 使用Callable和Future:创建一个实现了Callable接口的类,并实现call()方法,在call()方法中定义线程的执行逻辑。使用ExecutorService的submit()方法提交Callable任务,并通过Future对象获取任务的返回结果。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyCallable implements Callable<Integer> { public Integer call() { // 线程的执行逻辑,返回一个结果 return 1; } } public class Main { public static void main(String[] args) throws Exception { MyCallable callable = new MyCallable(); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Integer> future = executorService.submit(callable); int result = future.get(); // 获取任务的返回结果 System.out.println(result); executorService.shutdown(); } }
- 使用线程池:创建一个线程池,通过submit()方法提交Runnable或Callable任务,线程池会自动分配线程执行任务。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MyRunnable implements Runnable { public void run() { // 线程的执行逻辑 } } public class Main { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池 executorService.execute(new MyRunnable()); // 提交任务 executorService.shutdown(); // 关闭线程池 } }