← 返回首页

Java并发编程:线程安全与高效

📂 java ⏱ 3 min 422 words

Java并发编程:线程安全与高效

概述

Java并发编程提供了丰富的工具和机制来处理多线程环境下的复杂问题。掌握并发编程的核心概念,是开发高性能应用的关键。

1. volatile关键字

public class VolatileDemo {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            System.out.println("运行中...");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("已停止");
    }

    public void stop() {
        running = false;
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileDemo demo = new VolatileDemo();
        Thread t = new Thread(demo::run);
        t.start();
        Thread.sleep(500);
        demo.stop();
    }
}

2. Lock接口与ReentrantLock

import java.util.concurrent.locks.*;

public class ReentrantLockDemo {
    private final ReentrantLock lock = new ReentrantLock();
    private int balance = 1000;

    public void transfer(int amount) {
        lock.lock();
        try {
            if (balance >= amount) {
                balance -= amount;
                System.out.println("转账: " + amount + ", 余额: " + balance);
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo demo = new ReentrantLockDemo();
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    demo.transfer(100);
                }
            });
            threads[i].start();
        }
    }
}

3. CountDownLatch

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        int threadCount = 5;
        CountDownLatch latch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int taskId = i;
            new Thread(() -> {
                try {
                    System.out.println("任务" + taskId + "开始");
                    Thread.sleep(1000);
                    System.out.println("任务" + taskId + "完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }).start();
        }

        latch.await();
        System.out.println("所有任务完成");
    }
}

4. Semaphore信号量

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    private final Semaphore semaphore = new Semaphore(3);

    public void accessResource() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "获取资源");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName() + "释放资源");
        }
    }

    public static void main(String[] args) {
        SemaphoreDemo demo = new SemaphoreDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(demo::accessResource).start();
        }
    }
}

5. ConcurrentHashMap

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapDemo {
    private final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    public void increment(String key) {
        map.merge(key, 1, Integer::sum);
    }

    public int getCount(String key) {
        return map.getOrDefault(key, 0);
    }

    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMapDemo demo = new ConcurrentHashMapDemo();
        Thread[] threads = new Thread[10];

        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    demo.increment("counter");
                }
            });
            threads[i].start();
        }

        for (Thread t : threads) {
            t.join();
        }

        System.out.println("Count: " + demo.getCount("counter"));
    }
}

最佳实践

  1. 优先使用并发容器:ConcurrentHashMap替代Collections.synchronizedMap
  2. 使用不可变对象:天然线程安全
  3. 减少锁的粒度:细粒度锁提高并发性
  4. 使用volatile:保证可见性,不保证原子性
  5. 避免死锁:注意锁的获取顺序

总结

Java并发编程提供了丰富的工具和机制,掌握volatile、Lock、并发容器等核心组件,是开发高性能并发应用的基础。合理使用这些工具,可以有效提高程序的并发性和性能。