java中如何实现多线程
实现多线程的三种核心方法
继承Thread类
通过继承Thread类并重写run()方法定义线程任务。创建子类实例后调用start()方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running via inheritance");
}
}
// 启动线程
new MyThread().start();
实现Runnable接口
实现Runnable接口的run()方法,将实例作为参数传递给Thread构造函数。这种方式更灵活,推荐使用。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running via Runnable");
}
}
// 启动线程
new Thread(new MyRunnable()).start();
使用Callable和Future
适用于需要返回结果或抛出异常的线程任务。通过ExecutorService提交Callable任务,返回Future对象获取结果。
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> "Callable result");
System.out.println(future.get()); // 获取结果
executor.shutdown();
线程池管理
固定大小线程池
通过Executors.newFixedThreadPool(int)创建固定数量的线程池,避免频繁创建销毁线程的开销。
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
pool.execute(() -> System.out.println(Thread.currentThread().getName()));
}
pool.shutdown();
线程同步与安全
synchronized关键字
修饰方法或代码块,确保同一时间只有一个线程访问共享资源。
synchronized void criticalSection() {
// 线程安全代码
}
ReentrantLock显式锁
提供更灵活的锁控制,支持公平锁和中断等待。
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程间通信
wait()与notify()
通过Object类的wait()和notify()实现线程等待与唤醒。需在synchronized块中使用。
synchronized (lock) {
lock.wait(); // 释放锁并等待
lock.notify(); // 唤醒等待线程
}
现代并发工具
CompletableFuture异步编程
Java 8引入的异步编程工具,支持链式调用和组合异步任务。
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
并行流处理
利用parallelStream()实现集合数据的并行处理。
List<Integer> numbers = Arrays.asList(1, 2, 3);
numbers.parallelStream().forEach(n -> System.out.println(n * n));
每种方法适用于不同场景:简单任务可用Thread或Runnable;需返回值时用Callable;高并发场景优先选择线程池和并发工具类。同步机制确保数据一致性,而现代API如CompletableFuture简化了复杂异步逻辑的实现。







