高级线程模式

Java 代码优化

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

线程池基础

创建线程代价高!

$$

线程池:

  • 复用现有线程
  • 控制并发线程数
  • 通过 ExecutorService 接口管理
Java 代码优化

创建线程池

// Fixed thread pool with 4 threads
ExecutorService fixedPool = Executors.newFixedThreadPool(4);


// Cached thread pool that grows as needed ExecutorService cachedPool = Executors.newCachedThreadPool();
// Single-threaded executor ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
Java 代码优化

提交任务

ExecutorService executor = Executors.newFixedThreadPool(4);

// Submit a task with no return value
executor.execute(() -> System.out.println("Simple task"));

// Submit a task with a return value (Callable)
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

// Get result from Future (blocks until complete)
int result = future.get();
Java 代码优化

关闭执行器

// Signal shutdown, but continue running existing tasks
executor.shutdown();


// Wait for termination (with timeout) boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS);
// Force immediate shutdown, canceling running tasks executor.shutdownNow();
Java 代码优化

CompletableFuture 简介

  • CompletableFuture
  • 自 Java 8 起属于并发 API
  • 现代异步编程方式
  • 可手动完成或通过 Function 完成
  • 支持用回调链式操作
  • 可与显式线程池配合或独立使用
Java 代码优化

创建 CompletableFuture

// Run async with default executor
CompletableFuture<Void> runAsync = 
    CompletableFuture.runAsync(() -> performTask());

// Supply async with custom executor ExecutorService executor = Executors.newCachedThreadPool(); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> fetchData(), executor);
Java 代码优化

链式操作

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> fetchUserData(userId))
    .thenApply(data -> extractUsername(data))
    .exceptionally(ex -> "Unknown user");

// Access to result when ready
future.thenAccept(result -> System.out.println(result));
Java 代码优化

Vamos praticar!

Java 代码优化

Preparing Video For Download...