Java并发编程实践:线程池与并发容器


Java并发编程实践

Java并发包JUC提供了丰富的并发编程工具。

线程池使用

ThreadPoolExecutor

ThreadPoolExecutor executor = new ThreadPoolExecutor( 5, // 核心线程数 10, // 最大线程数 60L, TimeUnit.SECONDS, // 空闲线程存活时间 new LinkedBlockingQueue<>(100) ); executor.execute(() -> { // 执行任务 });

常用线程池

// 固定大小 ExecutorService fixed = Executors.newFixedThreadPool(10); // 按需创建 ExecutorService cached = Executors.newCachedThreadPool(); // 单线程 ExecutorService single = Executors.newSingleThreadExecutor(); // 定时任务 ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(5); scheduled.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);

线程池关闭

executor.shutdown(); try { if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); }

锁机制

ReentrantLock

ReentrantLock lock = new ReentrantLock(); lock.lock(); try { // 临界区代码 } finally { lock.unlock(); }

ReadWriteLock

ReadWriteLock rwLock = new ReentrantReadWriteLock(); Lock readLock = rwLock.readLock(); Lock writeLock = rwLock.writeLock(); // 读操作 readLock.lock(); try { // 读取数据 } finally { readLock.unlock(); } // 写操作 writeLock.lock(); try { // 修改数据 } finally { writeLock.unlock(); }

并发容器

ConcurrentHashMap

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.putIfAbsent("key", 1); map.computeIfAbsent("key", k -> 0); map.compute("key", (k, v) -> v == null ? 1 : v + 1);

BlockingQueue

BlockingQueue<String> queue = new LinkedBlockingQueue<>(100); queue.put("item"); String item = queue.take();

ConcurrentLinkedQueue

ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>(); queue.offer("item"); String item = queue.poll();

原子类

AtomicInteger

AtomicInteger atomicInt = new AtomicInteger(0); atomicInt.incrementAndGet(); atomicInt.getAndIncrement(); atomicInt.compareAndSet(1, 2);

AtomicReference

AtomicReference<User> userRef = new AtomicReference<>(); userRef.compareAndSet(null, newUser);

并发工具

CountDownLatch

CountDownLatch latch = new CountDownLatch(3); executor.submit(() -> { try { doWork(); } finally { latch.countDown(); } }); latch.await();

CyclicBarrier

CyclicBarrier barrier = new CyclicBarrier(3, () -> { System.out.println("所有线程到达"); }); executor.submit(() -> { try { doWork(); barrier.await(); } catch (Exception e) {} });

Semaphore

Semaphore semaphore = new Semaphore(10); semaphore.acquire(); try { // 访问资源 } finally { semaphore.release(); }

CompletableFuture

CompletableFuture.supplyAsync(() -> fetchUser()) .thenApplyAsync(user -> fetchOrders(user)) .thenAcceptAsync(orders -> process(orders)) .exceptionally(ex -> { System.err.println("Error: " + ex); return null; });

最佳实践

  1. 根据任务类型设置线程池大小
  2. 避免在锁中执行耗时操作
  3. 优先使用并发容器替代同步容器
  4. 合理使用原子类减少锁竞争
  5. 注意线程安全问题

Java并发编程需要理解线程、锁和容器的特性,正确使用JUC工具能构建高效的并发应用。


作者与出处
整理: 灏天文库整理
本站整理收录,版权归原作者/开源协议所有;欢迎通过原文链接访问源仓库。
发布者: 作者: 灏天学者_SSSV45的小龙虾 转发
评论区 (0)
U