在多线程应用中,如何通过线程间通信实现数据的同步和一致性?请举例说明。

在多线程应用中,线程间通信是实现数据同步和一致性的核心手段。Java 提供了多种机制来实现线程间通信,包括 synchronized 关键字、wait() 和 notify() 方法、Lock 和 Condition 接口、以及并发工具类如 BlockingQueue 等。以下是详细说明和示例:

1. 使用 synchronized 关键字

通过 synchronized 可以确保同一时间只有一个线程能访问共享资源,从而实现数据的同步。

示例:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
        System.out.println("当前值: " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter.increment();
            }
        });
        t1.start();
        t2.start();
    }
}

输出结果会是递增的,因为 synchronized 确保了 increment 方法的原子性。

2. 使用 wait() 和 notify() 方法

wait() 和 notify() 是基于对象的监视器机制实现的线程间通信。线程可以等待某个条件满足,而其他线程可以通过通知唤醒等待的线程。

示例:

public class SharedResource {
    private boolean flag = false;

    public synchronized void waitForFlag() throws InterruptedException {
        while (!flag) {
            wait();
        }
        System.out.println("标志已设置,继续执行。");
    }

    public synchronized void setFlag() {
        flag = true;
        notifyAll();
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();
        Thread t1 = new Thread(() -> {
            try {
                resource.waitForFlag();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
                resource.setFlag();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
    }
}

t1 线程会等待 t2 线程设置 flag 后才会继续执行。

3. 使用 Lock 和 Condition

Lock 提供了比 synchronized 更灵活的锁机制,结合 Condition 可以实现更复杂的线程间通信。

示例:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBuffer {
    private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();
    private final Object[] items = new Object[10];
    private int putIndex = 0, takeIndex = 0, count = 0;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                notFull.await();
            }
            items[putIndex] = x;
            if (++putIndex == items.length) putIndex = 0;
            count++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            Object x = items[takeIndex];
            if (++takeIndex == items.length) takeIndex = 0;
            count--;
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}

这是一个有界缓冲区的实现,生产者和消费者通过 Condition 实现线程安全。

4. 使用 BlockingQueue

BlockingQueue 是 Java 并发包中提供的线程安全的队列,适合生产者-消费者场景。

示例:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumer {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    queue.put(i);
                    System.out.println("生产: " + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    Integer item = queue.take();
                    System.out.println("消费: " + item);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();
    }
}

BlockingQueue 内部已经实现了线程同步,无需额外处理。

总结

线程间通信的核心是确保共享资源的线程安全性。synchronized、wait()/notify()、Lock/Condition 和 BlockingQueue 是常用的实现方式。选择合适的机制取决于具体的应用场景和对性能的需求。