
我将从Java并发编程的基础概念、关键机制、工具类等方面入手,为你提供一篇涵盖技术方案与应用实例的文章,助你备战2025年Java秋招面试。
并行是指多个任务在多个CPU核心上同时执行,这是物理上的同时进行。例如,一个拥有多个CPU核心的服务器,不同的核心可以同时处理不同的线程任务。并发则是指多个任务在单CPU核心上交替执行,从逻辑上看好像是同时进行。就像一个服务员在多个顾客之间轮流服务,虽然同一时刻只能服务一个顾客,但通过快速切换,让顾客感觉像是同时被服务。在Java中,通过多线程技术可以实现并发,而并行则依赖于硬件的多核心支持以及合理的线程调度。
继承Thread类是Java中创建线程的一种方式。通过重写Thread类的run()方法,将线程要执行的任务逻辑写在run()方法中。然后通过创建该类的实例,并调用start()方法来启动线程。例如:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程正在执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}这种方式的优点是简单直观,缺点是由于Java单继承的限制,该类不能再继承其他类。
实现Runnable接口是更为常用的创建线程方式。定义一个类实现Runnable接口,并实现其run()方法。然后将该类的实例作为参数传递给Thread类的构造函数,再调用start()方法启动线程。示例代码如下:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程正在执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}这种方式的好处是避免了单继承的限制,一个类可以同时实现多个接口,更加灵活。
实现Callable接口可以让线程有返回值并且能抛出异常。Callable接口中的call()方法定义了线程执行的任务,与Runnable接口的run()方法不同,call()方法有返回值。使用时,需要配合FutureTask类来获取线程执行的结果。示例如下:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
try {
Integer result = futureTask.get();
System.out.println("线程执行结果:" + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}Java线程有以下几种状态:
特性 | sleep() | wait() |
|---|---|---|
所属类 | Thread | Object |
锁行为 | 不释放锁 | 释放锁 |
唤醒方式 | 超时自动唤醒 | 需其他线程调用notify()唤醒 |
使用场景 | 线程休眠 | 线程间通信 |
sleep()方法是Thread类的静态方法,用于让当前线程暂停执行指定的时间,在休眠期间,线程不会释放它持有的锁。例如:
try {
Thread.sleep(1000); // 线程暂停1秒
} catch (InterruptedException e) {
e.printStackTrace();
}wait()方法是Object类的方法,必须在同步代码块中使用。当一个线程调用wait()方法时,它会释放当前持有的锁,并进入等待状态,直到其他线程调用该对象的notify()或notifyAll()方法唤醒它。例如:
synchronized (obj) {
try {
obj.wait(); // 线程等待,释放obj锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}进程是资源分配的最小单位,它拥有独立的内存空间、文件句柄等系统资源。每个进程在运行时,操作系统会为其分配独立的内存区域,不同进程之间的内存空间相互隔离。例如,我们运行的一个Java程序就是一个进程,它有自己独立的堆内存、方法区等。
线程是调度的最小单位,它共享进程的资源,如堆内存、方法区等,但每个线程有自己独立的栈和寄存器。多个线程可以并发执行,提高程序的执行效率。比如在一个Java Web应用中,多个用户的请求可以由不同的线程来处理,这些线程共享应用的堆内存和方法区中的数据。
协程是比线程更轻量级的概念,在Kotlin等语言中有很好的支持。协程可以在一个线程中实现类似多线程的并发效果,通过用户态的调度来切换执行,避免了线程上下文切换的开销。
当我们直接调用线程的run()方法时,它只是在当前线程中执行run()方法的代码,并没有创建新的线程,也就无法实现多线程并发的效果。例如:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.run(); // 直接调用run(),在main线程中执行
System.out.println("main线程执行完毕");
}
}而调用start()方法时,Java虚拟机(JVM)会创建一个新的线程,并在这个新线程中执行run()方法,从而实现多线程并发执行。例如:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动新线程执行run()
System.out.println("main线程执行完毕");
}
}在上述代码中,当调用start()方法后,会创建一个新线程来执行MyThread的run()方法,同时main线程也会继续向下执行,实现了并发效果。
ThreadLocal的主要作用是实现线程隔离,为每个线程提供独立的变量副本,避免共享数据在多线程环境下的冲突。例如,在一个Web应用中,每个用户的请求由不同的线程处理,如果需要在整个请求处理过程中存储一些与用户相关的上下文信息,如用户会话ID、用户权限等,使用ThreadLocal就可以方便地为每个线程提供独立的存储区域,各个线程之间的数据互不干扰。
每个线程都维护一个ThreadLocal.ThreadLocalMap对象,这个Map的键是ThreadLocal对象,值是线程变量。当一个线程通过ThreadLocal的get()方法获取变量时,它实际上是从自己的ThreadLocalMap中获取对应的值。例如:
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
int value = threadLocal.get();
value++;
threadLocal.set(value);
System.out.println("线程1:" + threadLocal.get());
});
Thread thread2 = new Thread(() -> {
int value = threadLocal.get();
value += 2;
threadLocal.set(value);
System.out.println("线程2:" + threadLocal.get());
});
thread1.start();
thread2.start();
}
}在上述代码中,thread1和thread2各自维护自己的ThreadLocalMap,它们对threadLocal变量的操作互不影响。
ThreadLocalMap中的键使用弱引用,这是为了防止内存泄漏。当ThreadLocal对象没有其他强引用指向它时,在垃圾回收时,键会被回收。但是如果没有及时调用remove()方法,对应的value可能会因为被ThreadLocalMap中的Entry强引用而无法被回收,从而导致内存泄漏。
如前所述,由于ThreadLocalMap中的键是弱引用,当ThreadLocal对象不再被其他地方引用时,在垃圾回收时键会被回收。但如果此时线程没有结束,且没有调用ThreadLocal的remove()方法,那么Entry中的value仍然被Entry强引用,导致value无法被回收,造成内存泄漏。例如:
public class MemoryLeakExample {
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Thread thread = new Thread(() -> {
threadLocal.set("大对象");
// 这里没有调用threadLocal.remove()
});
thread.start();
// 模拟线程长时间运行,导致ThreadLocal对象没有被及时回收
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadLocal = null; // ThreadLocal对象不再被强引用
// 此时如果线程没有结束,ThreadLocalMap中的value可能无法被回收,造成内存泄漏
}
}为了避免ThreadLocal内存泄漏问题,我们应该在使用完ThreadLocal变量后,在finally块中调用remove()方法,确保及时清理线程中的数据。例如:
public class FixedMemoryLeakExample {
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
threadLocal.set("大对象");
// 业务逻辑
} finally {
threadLocal.remove(); // 及时清理
}
});
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadLocal = null;
}
}通过这种方式,即使ThreadLocal对象不再被强引用,由于已经调用了remove()方法,ThreadLocalMap中对应的Entry也会被移除,避免了内存泄漏。
Java内存模型(JMM)定义了线程间共享变量的访问规则,其核心围绕解决原子性、可见性和有序性问题。在JMM中,所有的共享变量都存储在主内存中,每个线程都有自己私有的工作内存,线程对变量的所有操作都必须在自己的工作内存中进行,不能直接从主内存读写。例如,当一个线程修改了共享变量的值,首先是在自己的工作内存中修改,然后需要将修改后的值刷新回主内存,其他线程要获取最新值,也需要从主内存中读取。
原子性是指操作不可分割,要么全部执行成功,要么全部不执行。例如,对一个int类型变量的赋值操作i = 10;,在单线程环境下是原子操作,但在多线程环境下,如果没有适当的同步机制,可能会出现问题。而使用synchronized关键字修饰的代码块可以保证其原子性,在同一时刻只有一个线程能够进入该代码块执行。例如:
public class AtomicityExample {
private int count = 0;
public synchronized void increment() {
count++;
}
}在上述代码中,increment()方法被synchronized修饰,保证了count++操作的原子性,避免了多线程环境下的竞态条件。
可见性是指一个线程修改了共享变量的值,其他线程能够立即看到这个修改。在没有同步机制的情况下,线程对变量的修改可能不会及时刷新到主内存,导致其他线程读取到的是旧值。使用volatile关键字可以保证变量的可见性,它强制线程将修改后的值立即刷新到主内存,并且在读取变量时,也会从主内存中读取最新值。例如:
public class VisibilityExample {
private volatile boolean flag = false;
public void setFlag() {
flag = true;
}
public void checkFlag() {
if (flag) {
// 执行相应逻辑
}
}
}在上述代码中,当一个线程调用setFlag()方法修改flag的值后,其他线程调用checkFlag()方法能够立即看到修改后的结果。
有序性是指程序执行的顺序按照代码的先后顺序执行。但在实际执行中,为了提高性能,编译器和处理器可能会对指令进行重排序。例如:
int a = 10; // 语句1
int b = 20; // 语句2
int c = a + b; // 语句3在不影响最终结果的情况下,编译器或处理器可能会将语句1和语句2的执行顺序进行重排。使用volatile关键字可以禁止指令重排序,保证特定操作的顺序性。例如:
public class OrderingExample {
private volatile int a = 0;
private boolean flag = false;
public void write() {
a = 10; // 语句1
flag = true; // 语句2
}
public void read() {
if (flag) { // 语句3
int result = a * 2; // 语句4
}
}
}在上述代码中,由于flag被volatile修饰,当一个线程执行write()方法时,语句1和语句2的执行顺序不会被重排,并且在另一个线程执行read()方法时,能够保证语句3和语句4的执行顺序是基于正确的a值。
volatile的主要作用之一是保证可见性。当一个变量被volatile修饰时,线程对该变量的写操作会立即刷新到主内存,其他线程对该变量的读操作会从主内存中读取最新值,而不是从自己的工作内存中读取可能的旧值。例如,在一个多线程的计数器场景中:
public class VolatileCounter {
private volatile int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}多个线程调用increment()方法修改count值,其他线程调用getCount()方法能够获取到最新的count值,避免了由于工作内存数据不一致导致的问题。
volatile通过内存屏障实现有序性。在写操作后,会插入Store - Barrier指令,强制将修改后的值刷新到主内存,确保对该变量的操作
ReentrantLock是一个可重入的互斥锁,相比synchronized具有更灵活的锁机制。以下是一个使用ReentrantLock实现的生产者-消费者示例:
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerExample {
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 5;
public void produce(int item) throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) {
notFull.await(); // 队列满时等待
}
queue.offer(item);
System.out.println(Thread.currentThread().getName() + " 生产: " + item);
notEmpty.signal(); // 通知消费者队列非空
} finally {
lock.unlock();
}
}
public int consume() throws InterruptedException {
lock.lock();
try {
while (queue.isEmpty()) {
notEmpty.await(); // 队列空时等待
}
int item = queue.poll();
System.out.println(Thread.currentThread().getName() + " 消费: " + item);
notFull.signal(); // 通知生产者队列未满
return item;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProducerConsumerExample pc = new ProducerConsumerExample();
// 生产者线程
Thread producer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
pc.produce(i);
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "Producer");
// 消费者线程
Thread consumer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
pc.consume();
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "Consumer");
producer.start();
consumer.start();
}
}ReentrantLock可以创建公平锁和非公平锁。公平锁会按照线程请求锁的顺序来获取锁,而非公平锁则允许线程在锁释放时直接竞争锁,不考虑请求顺序。以下是创建公平锁的示例:
ReentrantLock fairLock = new ReentrantLock(true); // 创建公平锁Java的原子类提供了高效的原子操作,避免了使用锁的开销。以下是一个使用AtomicInteger实现计数器的示例:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
public static void main(String[] args) throws InterruptedException {
AtomicCounter counter = new AtomicCounter();
int threadCount = 10;
Thread[] threads = new Thread[threadCount];
// 创建并启动多个线程
for (int i = 0; i < threadCount; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
// 等待所有线程完成
for (Thread thread : threads) {
thread.join();
}
System.out.println("最终计数: " + counter.getCount()); // 输出应为10000
}
}原子类的底层实现基于CAS(Compare - And - Swap)操作。CAS是一种无锁算法,包含三个操作数:内存位置(V)、预期原值(A)和新值(B)。如果内存位置的值与预期原值相匹配,那么处理器会自动将该位置值更新为新值。以下是一个简单的CAS操作示例:
import java.util.concurrent.atomic.AtomicInteger;
public class CASExample {
private AtomicInteger value = new AtomicInteger(10);
public void compareAndSet(int expected, int newValue) {
boolean success = value.compareAndSet(expected, newValue);
System.out.println("操作结果: " + success);
}
public static void main(String[] args) {
CASExample example = new CASExample();
example.compareAndSet(10, 20); // 操作成功,值变为20
example.compareAndSet(10, 30); // 操作失败,值仍为20
}
}ConcurrentHashMap是线程安全的哈希表实现,在多线程环境下可以高效地进行读写操作。以下是一个使用ConcurrentHashMap的示例:
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
public void add(String key, int value) {
map.put(key, value);
}
public int get(String key) {
return map.getOrDefault(key, 0);
}
public void remove(String key) {
map.remove(key);
}
public static void main(String[] args) {
ConcurrentHashMapExample example = new ConcurrentHashMapExample();
// 多个线程并发操作map
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.add("key" + i, i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
int value = example.get("key" + i);
System.out.println("key" + i + ": " + value);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}CopyOnWriteArrayList是一个线程安全的列表实现,它在修改操作时会创建底层数组的一个副本,从而避免了在迭代过程中出现ConcurrentModificationException。以下是一个使用CopyOnWriteArrayList的示例:
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample {
private CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
public void add(String element) {
list.add(element);
}
public void iterate() {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public static void main(String[] args) {
CopyOnWriteArrayListExample example = new CopyOnWriteArrayListExample();
// 线程1添加元素
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
example.add("element" + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 线程2迭代列表
Thread t2 = new Thread(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
example.iterate();
});
t1.start();
t2.start();
}
}线程池可以有效地管理和复用线程,提高系统性能。以下是一个使用Executors工厂类创建线程池的示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(3);
// 提交任务到线程池
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("任务 " + taskId + " 执行完成");
});
}
// 关闭线程池
executor.shutdown();
try {
// 等待所有任务完成
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
// 超时后强制关闭
executor.shutdownNow();
}
} catch (InterruptedException e) {
// 再次调用shutdownNow
executor.shutdownNow();
}
}
}实际生产环境中,推荐使用ThreadPoolExecutor类来自定义线程池,以满足特定需求。以下是一个自定义线程池的示例:
import java.util.concurrent.*;
public class CustomThreadPoolExample {
public static void main(String[] args) {
// 创建自定义线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // 核心线程数
5, // 最大线程数
60, // 线程空闲时间
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10), // 任务队列
Executors.defaultThreadFactory(), // 线程工厂
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);
// 提交任务
for (int i = 0; i < 20; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// 关闭线程池
executor.shutdown();
}
}Semaphore是一个计数信号量,用于控制同时访问某个资源的线程数量。以下是一个使用Semaphore实现资源池的示例:
import java.util.concurrent.Semaphore;
public class ResourcePool {
private final Semaphore semaphore;
private final int maxResources;
private final boolean[] resources;
public ResourcePool(int maxResources) {
this.maxResources = maxResources;
this.resources = new boolean[maxResources];
this.semaphore = new Semaphore(maxResources, true); // 创建公平信号量
}
public int acquire() throws InterruptedException {
semaphore.acquire(); // 获取许可
return getResource();
}
public void release(int resourceId) {
markResourceAsFree(resourceId);
semaphore.release(); // 释放许可
}
private synchronized int getResource() {
for (int i = 0; i < maxResources; i++) {
if (!resources[i]) {
resources[i] = true;
return i;
}
}
return -1; // 不会发生,因为已经获取了许可
}
private synchronized void markResourceAsFree(int resourceId) {
resources[resourceId] = false;
}
public static void main(String[] args) {
ResourcePool pool = new ResourcePool(3);
// 创建10个线程竞争资源
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
int resourceId = pool.acquire();
System.out.println(Thread.currentThread().getName() + " 获取资源 " + resourceId);
Thread.sleep(1000);
pool.release(resourceId);
System.out.println(Thread.currentThread().getName() + " 释放资源 " + resourceId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "Thread-" + i).start();
}
}
}CountDownLatch用于让一个或多个线程等待其他线程完成操作。以下是一个使用CountDownLatch的示例:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int workerCount = 5;
CountDownLatch latch = new CountDownLatch(workerCount);
// 创建并启动多个工作线程
for (int i = 0; i < workerCount; i++) {
final int workerId = i;
new Thread(() -> {
System.out.println("工作线程 " + workerId + " 开始工作");
try {
// 模拟工作
Thread.sleep((long) (Math.random() * 5000));
System.out.println("工作线程 " + workerId + " 完成工作");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown(); // 计数减1
}
}).start();
}
// 主线程等待所有工作线程完成
System.out.println("主线程等待工作线程完成...");
latch.await();
System.out.println("所有工作线程已完成,主线程继续执行");
}
}CyclicBarrier用于让一组线程到达一个屏障(同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续执行。以下是一个使用CyclicBarrier的示例:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
int threadCount = 3;
CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> {
System.out.println("所有线程都到达屏障,继续执行");
});
// 创建并启动多个线程
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
new Thread(() -> {
System.out.println("线程 " + threadId + " 开始执行");
try {
// 模拟工作
Thread.sleep((long) (Math.random() * 3000));
System.out.println("线程 " + threadId + " 到达屏障");
barrier.await(); // 等待其他线程到达屏障
System.out.println("线程 " + threadId + " 继续执行");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}Exchanger用于两个线程之间交换数据。以下是一个使用Exchanger的示例:
import java.util.concurrent.Exchanger;
public class ExchangerExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
// 第一个线程
Thread thread1 = new Thread(() -> {
try {
String data1 = "线程1的数据";
System.out.println("线程1发送: " + data1);
String receivedData = exchanger.exchange(data1);
System.out.println("线程1接收: " + receivedData);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 第二个线程
Thread thread2 = new Thread(() -> {
try {
String data2 = "线程2的数据";
System.out.println("线程2发送: " + data2);
String receivedData = exchanger.exchange(data2);
System.out.println("线程2接收: " + receivedData);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
thread1.start();
thread2.start();
}
}CompletableFuture是Java 8引入的用于处理异步计算的类,它可以方便地构建异步任务链。以下是一个使用CompletableFuture的示例:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建自定义线程池
var executor = Executors.newFixedThreadPool(2);
// 异步任务1:获取用户ID
CompletableFuture<String> userIdFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("获取用户ID");
return "user123";
}, executor);
// 异步任务2:根据用户ID获取订单信息
CompletableFuture<String> orderFuture = userIdFuture.thenApplyAsync(userId -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("获取用户 " + userId + " 的订单信息");
return "order456";
}, executor);
// 异步任务3:根据订单信息获取物流信息
CompletableFuture<String> logisticsFuture = orderFuture.thenApplyAsync(orderId -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("获取订单 " + orderId + " 的物流信息");
return "物流信息:已发货";
}, executor);
// 最终结果处理
logisticsFuture.thenAccept(logisticsInfo -> {
System.out.println("最终结果:" + logisticsInfo);
executor.shutdown();
});
// 主线程不需要等待,可以继续执行其他任务
System.out.println("主线程继续执行");
}
}CompletableFuture提供了多种方法来组合多个异步任务。以下是一个组合多个CompletableFuture的示例:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureCombinationExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 任务1:计算两个数的和
CompletableFuture<Integer> task1 = CompletableFuture.supplyAsync(() -> 2 + 3);
// 任务2:计算两个数的乘积
CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> 4 * 5);
// 组合两个任务的结果
CompletableFuture<Integer> combinedFuture = task1.thenCombine(task2, (sum, product) -> sum + product);
// 获取最终结果
System.out.println("最终结果: " + combinedFuture.get()); // 输出: 25
}
}Reactor是Java生态中主流的响应式编程框架,基于Reactive Streams规范。以下是一个使用Reactor的简单示例:
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
public class ReactorExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个Flux,发出1到5的整数
Flux<Integer> numbers = Flux.range(1, 5);
// 对每个元素进行平方操作,并在另一个线程上执行
Flux<Integer> squaredNumbers = numbers
.publishOn(Schedulers.boundedElastic())
.map(n -> {
System.out.println("处理元素 " + n + " 在线程 " + Thread.currentThread().getName());
return n * n;
});
// 订阅并处理结果
squaredNumbers.subscribe(
num -> System.out.println("收到元素: " + num),
error -> System.err.println("错误: " + error),
() -> System.out.println("处理完成")
);
// 创建一个Mono,延迟1秒后发出一个值
Mono.just("Hello, Reactor!")
.delayElement(Duration.ofSeconds(1))
.subscribe(System.out::println);
// 主线程等待,以便异步操作有时间完成
Thread.sleep(2000);
}
}响应式编程中的背压是处理生产者与消费者速度不匹配的机制。以下是一个使用背压的示例:
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
public class BackpressureExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个快速生产者,每秒发出1000个元素
Flux<Integer> fastProducer = Flux.interval(Duration.ofMillis(1))
.map(i -> {
System.out.println("生产者发出: " + i);
return i.intValue();
});
// 创建一个慢速消费者,每500毫秒处理一个元素
fastProducer
.onBackpressureBuffer(100) // 设置缓冲区大小为100
.publishOn(Schedulers.boundedElastic(), 1) // 每次只请求1个元素
.subscribe(
item -> {
try {
Thread.sleep(500);
System.out.println("消费者处理: " + item);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
},
error -> System.err.println("错误: " + error.getMessage())
);
// 主线程等待
Thread.sleep(10000);
}
}Project Loom是Java平台上的一个重大改进,引入了轻量级线程(协程)的概念。以下是一个使用协程的示例:
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VirtualThreadExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个虚拟线程执行器
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
// 提交大量任务
for (int i = 0; i < 10000; i++) {
final int taskId = i;
executor.submit(() -> {
try {
// 模拟IO操作
Thread.sleep(Duration.ofMillis(100));
System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// 关闭执行器
executor.shutdown();
executor.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES);
}
}以下是一个简单的对比示例,展示协程在处理大量并发任务时的优势:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadVsVirtualThreadComparison {
private static final int TASK_COUNT = 100000;
public static void main(String[] args) throws InterruptedException {
// 测试传统线程
testTraditionalThreads();
// 测试虚拟线程
testVirtualThreads();
}
private static void testTraditionalThreads() throws InterruptedException {
long startTime = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(200);
for (int i = 0; i < TASK_COUNT; i++) {
final int taskId = i;
executor.submit(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
long endTime = System.currentTimeMillis();
System.out.println("传统线程耗时: " + (endTime - startTime) + " ms");
}
private static void testVirtualThreads() throws InterruptedException {
long startTime = System.currentTimeMillis();
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
for (int i = 0; i < TASK_COUNT; i++) {
final int taskId = i;
executor.submit(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
long endTime = System.currentTimeMillis();
System.out.println("虚拟线程耗时: " + (endTime - startTime) + " ms");
}
}以下是一个检测死锁的示例代码:
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
public class DeadlockDetector {
private static final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
public static void start() {
Thread detector = new Thread(() -> {
while (true) {
long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
if (deadlockedThreads != null) {
ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(deadlockedThreads);
System.err.println("发现死锁!");
for (ThreadInfo info : threadInfos) {
System.err.println(info);
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
detector.setDaemon(true);
detector.start();
}
public static void main(String[] args) {
// 启动死锁检测器
start();
// 模拟死锁
Object lock1 = new Object();
Object lock2 = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("线程1获取了锁1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized (lock2) {
System.out.println("线程1获取了锁2");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println("线程2获取了锁2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized (lock1) {
System.out.println("线程2获取了锁1");
}
}
});
t1.start();
t2.start();
}
}// 双重检查锁定实现线程安全的单例模式
public class Singleton {
private static volatile Singleton instance; // 使用volatile保证可见性和有序性
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // 第一次检查
synchronized (Singleton.class) {
if (instance == null) { // 第二次检查
instance = new Singleton();
}
}
}
return instance;
}
}可以使用多种方式实现生产者-消费者模式,以下是使用BlockingQueue的实现:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerWithBlockingQueue {
private static final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
public static void main(String[] args) {
// 生产者线程
Thread producer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
queue.put(i);
System.out.println("生产者生产: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
Integer item = queue.take();
System.out.println("消费者消费: " + item);
Thread.sleep(200);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
}
}优化高并发场景下的性能可以从以下几个方面入手:
处理分布式系统中的并发问题可以采用以下方法:
import java.util.LinkedList;
import java.util.Queue;
public class SimpleThreadPool {
private final int poolSize;
private final WorkerThread[] workers;
private final Queue<Runnable> taskQueue;
private boolean isShutdown = false;
public SimpleThreadPool(int poolSize) {
this.poolSize = poolSize;
this.taskQueue = new LinkedList<>();
this.workers = new WorkerThread[poolSize];
// 初始化工作线程
for (int i = 0; i < poolSize; i++) {
workers[i] = new WorkerThread();
workers[i].start();
}
}
public synchronized void execute(Runnable task) {
if (isShutdown) {
throw new IllegalStateException("线程池已关闭");
}
taskQueue.add(task);
notify(); // 唤醒等待的工作线程
}
public synchronized void shutdown() {
isShutdown = true;
for (WorkerThread worker : workers) {
worker.interrupt();
}
}
private class WorkerThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
Runnable task;
synchronized (SimpleThreadPool.this) {
while (taskQueue.isEmpty() && !isShutdown) {
try {
wait(); // 没有任务时等待
} catch (InterruptedException e) {
interrupt();
}
}
if (isShutdown && taskQueue.isEmpty()) {
break;
}
task = taskQueue.poll();
}
if (task != null) {
try {
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
SimpleThreadPool threadPool = new SimpleThreadPool(3);
// 提交任务
for (int i = 0; i < 10; i++) {
final int taskId = i;
threadPool.execute(() -> {
System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// 关闭线程池
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPool.shutdown();
}
}import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncDataAggregation {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
// 模拟从不同服务获取数据
CompletableFuture<String> userInfoFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "用户信息:ID=123,姓名=张三";
}, executor);
CompletableFuture<String> orderInfoFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "订单信息:订单号=456,金额=100.00元";
}, executor);
CompletableFuture<String> paymentInfoFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "支付信息:支付方式=支付宝,状态=已支付";
}, executor);
// 聚合所有数据
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
userInfoFuture, orderInfoFuture, paymentInfoFuture
);
// 当所有任务完成后,处理结果
CompletableFuture<String> combinedFuture = allFutures.thenApply(v -> {
try {
return userInfoFuture.get() + "\n" +
orderInfoFuture.get() + "\n" +
paymentInfoFuture.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
// 获取最终结果
System.out.println("聚合结果:\n" + combinedFuture.get());
// 关闭线程池
executor.shutdown();
}
}Java并发编程是Java技术栈中非常重要的一部分,也是面试中的高频考点。本文从基础概念、关键机制、工具类、高级技术等多个方面进行了介绍,并提供了丰富的实操示例。希望通过本文的学习,你能够掌握Java并发编程的核心知识,在面试中取得好成绩。同时,在实际工作中,也能够运用这些知识设计和实现高效、稳定的并发系统。
Java 并发编程,Java 秋招面试题,多线程,线程池,并发集合,锁机制,volatile,synchronized,Atomic 类,JMM,JUC 包,ThreadLocal,CountDownLatch,CyclicBarrier,FutureTask
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。