java如何实现并发
实现Java并发的几种方法
Java提供了多种机制来实现并发编程,每种方法适用于不同的场景。以下是常见的实现方式:
使用Thread类
继承Thread类并重写run方法可以创建线程:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
实现Runnable接口是更常用的方式,因为Java不支持多重继承:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running");
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
使用Executor框架
Executor框架提供了线程池管理,比直接创建线程更高效:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
使用Callable和Future
Callable可以返回结果和抛出异常,配合Future使用:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
return "Callable result";
});
System.out.println(future.get());
executor.shutdown();
使用Fork/Join框架
适合处理可以递归分解的任务:
class FibonacciTask extends RecursiveTask<Integer> {
final int n;
FibonacciTask(int n) { this.n = n; }
protected Integer compute() {
if (n <= 1) return n;
FibonacciTask f1 = new FibonacciTask(n - 1);
f1.fork();
FibonacciTask f2 = new FibonacciTask(n - 2);
return f2.compute() + f1.join();
}
}
ForkJoinPool pool = new ForkJoinPool();
int result = pool.invoke(new FibonacciTask(10));
使用并发集合
Java提供线程安全的集合类如ConcurrentHashMap:
ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
int value = map.get("key");
使用同步机制
同步代码块和同步方法保证线程安全:

class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
使用Lock接口
比synchronized更灵活的锁机制:
Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
使用原子变量
java.util.concurrent.atomic包提供原子操作:
AtomicInteger atomicInt = new AtomicInteger(0);
atomicInt.incrementAndGet();
使用CompletableFuture
Java 8引入的异步编程工具:
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
每种并发实现方法都有其适用场景,需要根据具体需求选择最合适的方案。线程安全和性能是需要重点考虑的因素。






