Python 并发编程详解 - Java 开发者视角

Python入门基础教程(非常详细) Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,坚持「极简主义」。Python类库(模块)极其丰富,这使得Python几乎无所不能,不管是传统的Web开发、PC软件开发、Linux运维,还是当下火热的机器学习、大数据分析、网络爬虫,Python都能胜任。这套Python基础教程不是教科书,不会玩弄概念,而是力求口语化和通俗化,让读者尽快入门。如果有小朋友出于兴趣学习Python,请引导他阅读本教程的前半部分,这是基础,可以降低学习成本;... 阅读详情

Python 并发编程详解 - Java 开发者视角

在这里插入图片描述

📌 目标读者:有 Java 背景的开发者
🎯 核心目标:通过 Java 对比,理解 Python 并发编程模型
⏱️ 预计时间:30-45 分钟


📖 目录

  1. 核心概念对照
  2. [Python 并发模型演进](#python 并发模型演进)
  3. [async/await 深度解析](#asyncawait 深度解析)
  4. 实战示例
  5. 常见陷阱与最佳实践
  6. 总结对比表

1️⃣ 核心概念对照

Java vs Python 并发模型

特性JavaPython
线程模型操作系统级线程(内核线程)用户级线程(协程)+ GIL 限制
并发原语Thread, Runnable, ExecutorServicethreading, multiprocessing, asyncio
异步编程CompletableFuture, Reactive Streamsasync/await, asyncio
锁机制synchronized, ReentrantLockthreading.Lock, asyncio.Lock
内存模型JMM (Java Memory Model)GIL + 引用计数
适用场景CPU 密集型、IO 密集型IO 密集型(受 GIL 限制)

2️⃣ Python 并发模型演进

阶段 1:多线程时代(类似 Java)

# ❌ Python 多线程(受 GIL 限制,不适合 CPU 密集型)
import threading
import time

def task(name, seconds):
    print(f"{name} 开始执行")
    time.sleep(seconds)  # 模拟 IO 操作
    print(f"{name} 完成")

# 创建线程(类似 Java Thread)
t1 = threading.Thread(target=task, args=("任务 1", 2))
t2 = threading.Thread(target=task, args=("任务 2", 3))

t1.start()
t2.start()
t1.join()
t2.join()

print("所有任务完成")

对应 Java 代码:

// Java 多线程
Thread t1 = new Thread(() -> {
    System.out.println("任务 1 开始执行");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("任务 1 完成");
});

Thread t2 = new Thread(() -> {
    System.out.println("任务 2 开始执行");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("任务 2 完成");
});

t1.start();
t2.start();
try {
    t1.join();
    t2.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

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

关键区别:

  • ✅ Java 线程:真正的并行(多核利用)
  • ⚠️ Python 线程:受 GIL 限制,同一时刻只有一个线程在执行 Python 字节码
  • 💡 Python 多线程适合 IO 密集型(文件、网络),不适合 CPU 密集型

阶段 2:多进程(突破 GIL 限制)

# ✅ CPU 密集型任务:使用多进程
from multiprocessing import Process, Pool
import os

def cpu_intensive_task(n):
    print(f"进程 {os.getpid()} 正在计算...")
    result = sum(i * i for i in range(n))
    print(f"进程 {os.getpid()} 完成")
    return result

if __name__ == "__main__":
    # 方式 1: Process 类(类似 Java ProcessBuilder)
    p1 = Process(target=cpu_intensive_task, args=(10000000,))
    p2 = Process(target=cpu_intensive_task, args=(10000000,))
    
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    
    # 方式 2: 进程池(类似 Java ThreadPoolExecutor)
    with Pool(processes=4) as pool:
        results = pool.map(cpu_intensive_task, [10000000] * 4)
        print(f"结果:{results}")

对应 Java 代码:

// Java 进程池(ExecutorService)
ExecutorService executor = Executors.newFixedThreadPool(4);

List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 4; i++) {
    Future<Integer> future = executor.submit(() -> {
        System.out.println("进程 " + Thread.currentThread().getName() + " 正在计算...");
        int result = IntStream.range(0, 10_000_000)
                              .map(i -> i * i)
                              .sum();
        System.out.println("进程 " + Thread.currentThread().getName() + " 完成");
        return result;
    });
    futures.add(future);
}

// 收集结果
List<Integer> results = new ArrayList<>();
for (Future<Integer> future : futures) {
    try {
        results.add(future.get());  // 阻塞等待结果
    } catch (Exception e) {
        e.printStackTrace();
    }
}

executor.shutdown();

阶段 3:异步 IO(asyncio)⭐ 重点

这是 Python 3.5+ 的核心并发模型,也是本文的重点!

# ✅ IO 密集型任务的最佳选择
import asyncio

async def fetch_data(url, delay):
    """异步函数(协程)"""
    print(f"开始请求:{url}")
    await asyncio.sleep(delay)  # 非阻塞等待
    print(f"完成请求:{url}")
    return f"数据:{url}"

async def main():
    # 创建任务(类似 Java CompletableFuture)
    task1 = asyncio.create_task(fetch_data("https://api.example.com/users", 2))
    task2 = asyncio.create_task(fetch_data("https://api.example.com/posts", 3))
    
    # 等待所有任务完成(类似 Java CompletableFuture.allOf)
    results = await asyncio.gather(task1, task2)
    
    print(f"所有结果:{results}")

# 运行事件循环
asyncio.run(main())

对应 Java 代码(CompletableFuture):

// Java 异步编程
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
    System.out.println("开始请求:https://api.example.com/users");
    try {
        Thread.sleep(2000);  // 模拟网络延迟
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("完成请求:https://api.example.com/users");
    return "数据:https://api.example.com/users";
});

CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
    System.out.println("开始请求:https://api.example.com/posts");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("完成请求:https://api.example.com/posts");
    return "数据:https://api.example.com/posts";
});

// 等待所有任务完成
CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2);

// 获取结果
allTasks.thenRun(() -> {
    try {
        List<String> results = List.of(task1.get(), task2.get());
        System.out.println("所有结果:" + results);
    } catch (Exception e) {
        e.printStackTrace();
    }
}).join();  // 阻塞等待完成

3️⃣ async/await 深度解析

3.1 什么是 async/await?

Python 版本
# async 关键字:声明一个函数是异步函数(协程)
async def get_user(user_id):
    """异步函数定义"""
    # await 关键字:等待异步操作完成
    user = await database.query("SELECT * FROM users WHERE id = ?", user_id)
    return user

# 调用异步函数
async def main():
    user = await get_user(123)
    print(user)

asyncio.run(main())
Java 对比
// Java 没有直接的 async/await 语法糖(但有 Project Loom 在开发中)
// 最接近的是 CompletableFuture

public CompletableFuture<User> getUser(int userId) {
    return CompletableFuture.supplyAsync(() -> {
        // 模拟数据库查询
        return database.query("SELECT * FROM users WHERE id = ?", userId);
    });
}

// 调用
getUser(123)
    .thenAccept(user -> System.out.println(user))
    .join();  // 阻塞等待

关键区别:

  • ✅ Python async/await:语法糖,代码看起来像同步代码
  • ⚠️ Java CompletableFuture:链式调用,嵌套多层时较复杂
  • 💡 Python 更易读,Java 更显式

3.2 Event Loop(事件循环)vs ExecutorService

Python Event Loop
import asyncio

# Event Loop 是 Python 异步的核心
# 它负责调度和运行所有协程

async def task1():
    print("任务 1 开始")
    await asyncio.sleep(1)
    print("任务 1 完成")

async def task2():
    print("任务 2 开始")
    await asyncio.sleep(2)
    print("任务 2 完成")

async def main():
    # 创建两个任务
    t1 = asyncio.create_task(task1())
    t2 = asyncio.create_task(task2())
    
    # 等待所有任务
    await asyncio.gather(t1, t2)

# asyncio.run() 会创建并运行一个 Event Loop
asyncio.run(main())

Event Loop 工作原理:

┌─────────────────────────────────────┐
│       Event Loop (事件循环)          │
│                                     │
│  while True:                        │
│      # 1. 检查就绪的任务             │
│      ready_tasks = check_ready()    │
│                                     │
│      # 2. 执行就绪任务               │
│      for task in ready_tasks:       │
│          task.step()  # 执行一步     │
│                                     │
│      # 3. 处理 IO 事件                │
│      handle_io_events()             │
│                                     │
│      # 4. 调度延迟任务               │
│      schedule_delayed_tasks()       │
└─────────────────────────────────────┘
Java ExecutorService
// Java 使用 ExecutorService 管理线程池
ExecutorService executor = Executors.newFixedThreadPool(4);

// 提交任务
Future<?> future1 = executor.submit(() -> {
    System.out.println("任务 1 执行");
});

Future<?> future2 = executor.submit(() -> {
    System.out.println("任务 2 执行");
});

// 关闭线程池
executor.shutdown();

对比表:

特性Python Event LoopJava ExecutorService
线程模型单线程 + 协程多线程池
调度方式协作式(任务主动让出 CPU)抢占式(操作系统调度)
适用场景高并发 IO 密集型CPU 密集型 + IO 密集型
性能特点轻量级,百万级并发较重,千级并发

3.3 Await 的本质:不是阻塞,是暂停!

这是 Java 开发者最容易误解的地方!

# ❌ 错误理解:await = 阻塞
async def wrong_understanding():
    print("开始")
    result = await some_async_call()  # ← 以为这里会阻塞整个线程
    print("这行代码不会执行")  # ✅ 实际上会执行!

# ✅ 正确理解:await = 暂停当前任务,但释放线程
async def correct_understanding():
    print("任务 A 开始")
    
    # 遇到 await:
    # 1. 暂停这个任务的执行
    # 2. 把线程让给其他任务使用
    # 3. 当异步操作完成后,自动唤醒继续执行
    result = await some_async_call()
    
    # ✅ 这行代码会在异步操作完成后执行!
    print(f"结果是:{result}")

Java 对比:

// Java 的 Future.get() 是真正的阻塞
public void blockingExample() {
    Future<String> future = executor.submit(() -> {
        return "结果";
    });
    
    System.out.println("开始等待");
    String result = future.get();  // ❌ 阻塞!线程被占用
    System.out.println("获得结果:" + result);
}

// CompletableFuture.thenApply() 是非阻塞的
public void nonBlockingExample() {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
        return "结果";
    });
    
    future.thenApply(result -> {
        // ✅ 这个回调会在未来某个时刻执行
        System.out.println("获得结果:" + result);
    });
    
    System.out.println("主线程继续执行其他工作...");
}

关键要点:

  • ✅ Python await = Java CompletableFuture.thenApply()(非阻塞)
  • ❌ Python await ≠ Java Future.get()(阻塞)

4️⃣ 实战示例

示例 1:并发调用多个 API

Python 版本
import asyncio
import aiohttp  # 异步 HTTP 客户端

async def fetch_user(session, user_id):
    """异步获取用户信息"""
    url = f"https://api.example.com/users/{user_id}"
    async with session.get(url) as response:
        return await response.json()

async def fetch_post(session, post_id):
    """异步获取帖子信息"""
    url = f"https://api.example.com/posts/{post_id}"
    async with session.get(url) as response:
        return await response.json()

async def main():
    async with aiohttp.ClientSession() as session:
        # 方式 1: 顺序执行(慢!)
        print("=== 顺序执行 ===")
        user1 = await fetch_user(session, 1)  # 等待 1 秒
        post1 = await fetch_post(session, 1)  # 等待 1 秒
        # 总耗时:2 秒
        
        # 方式 2: 并发执行(快!)
        print("=== 并发执行 ===")
        tasks = [
            fetch_user(session, 1),
            fetch_post(session, 1),
            fetch_user(session, 2),
            fetch_post(session, 2),
        ]
        
        # 所有请求同时发出
        results = await asyncio.gather(*tasks)
        # 总耗时:~1 秒(取决于最慢的请求)
        
        print(f"获取到 {len(results)} 条数据")

asyncio.run(main())
Java 版本
import java.net.http.*;
import java.time.Duration;

public class ConcurrentApiCalls {
    
    private final HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build();
    
    public CompletableFuture<String> fetchUser(int userId) {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.example.com/users/" + userId))
            .GET()
            .build();
        
        return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body);
    }
    
    public CompletableFuture<String> fetchPost(int postId) {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.example.com/posts/" + postId))
            .GET()
            .build();
        
        return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body);
    }
    
    public void sequential() throws Exception {
        // 方式 1: 顺序执行
        System.out.println("=== 顺序执行 ===");
        String user1 = fetchUser(1).get();  // 等待 1 秒
        String post1 = fetchPost(1).get();  // 等待 1 秒
        // 总耗时:2 秒
    }
    
    public void concurrent() throws Exception {
        // 方式 2: 并发执行
        System.out.println("=== 并发执行 ===");
        
        CompletableFuture<String> user1Future = fetchUser(1);
        CompletableFuture<String> post1Future = fetchPost(1);
        CompletableFuture<String> user2Future = fetchUser(2);
        CompletableFuture<String> post2Future = fetchPost(2);
        
        // 等待所有完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
            user1Future, post1Future, user2Future, post2Future
        );
        
        allFutures.join();  // 阻塞等待所有完成
        
        // 获取结果
        List<String> results = List.of(
            user1Future.get(),
            post1Future.get(),
            user2Future.get(),
            post2Future.get()
        );
        
        System.out.println("获取到 " + results.size() + " 条数据");
        // 总耗时:~1 秒
    }
}

示例 2:生产者 - 消费者模式

Python 版本(使用 Queue)
import asyncio

async def producer(queue, name, count):
    """生产者:生产数据放入队列"""
    for i in range(count):
        item = f"{name}-产品-{i}"
        await queue.put(item)  # 异步放入
        print(f"{name} 生产了:{item}")
        await asyncio.sleep(0.5)  # 模拟生产时间

async def consumer(queue, name):
    """消费者:从队列取出数据处理"""
    while True:
        item = await queue.get()  # 异步取出
        
        if item is None:  # 毒丸信号,结束消费
            queue.task_done()
            break
        
        print(f"{name} 正在处理:{item}")
        await asyncio.sleep(1)  # 模拟处理时间
        queue.task_done()  # 标记任务完成

async def main():
    # 创建队列(类似 Java BlockingQueue)
    queue = asyncio.Queue(maxsize=10)
    
    # 创建生产者
    producer1 = asyncio.create_task(producer(queue, "工厂 A", 5))
    producer2 = asyncio.create_task(producer(queue, "工厂 B", 5))
    
    # 创建消费者
    consumer1 = asyncio.create_task(consumer(queue, "工人 1"))
    consumer2 = asyncio.create_task(consumer(queue, "工人 2"))
    
    # 等待生产者完成
    await producer1
    await producer2
    
    # 发送毒丸信号
    await queue.put(None)
    await queue.put(None)
    
    # 等待队列清空
    await queue.join()
    
    # 等待消费者完成
    await consumer1
    await consumer2

asyncio.run(main())
Java 版本(使用 BlockingQueue)
import java.util.concurrent.*;

public class ProducerConsumer {
    
    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
    
    class Producer implements Runnable {
        private final String name;
        private final int count;
        
        public Producer(String name, int count) {
            this.name = name;
            this.count = count;
        }
        
        @Override
        public void run() {
            try {
                for (int i = 0; i < count; i++) {
                    String item = name + "-产品-" + i;
                    queue.put(item);  // 阻塞放入
                    System.out.println(name + " 生产了:" + item);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
    
    class Consumer implements Runnable {
        private final String name;
        
        public Consumer(String name) {
            this.name = name;
        }
        
        @Override
        public void run() {
            try {
                while (true) {
                    String item = queue.take();  // 阻塞取出
                    
                    if (item == null) {  // 毒丸信号
                        queue.taskDone();
                        break;
                    }
                    
                    System.out.println(name + " 正在处理:" + item);
                    Thread.sleep(1000);
                    queue.taskDone();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
    
    public void run() throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        
        // 启动生产者
        executor.submit(new Producer("工厂 A", 5));
        executor.submit(new Producer("工厂 B", 5));
        
        // 启动消费者
        executor.submit(new Consumer("工人 1"));
        executor.submit(new Consumer("工人 2"));
        
        // 等待完成...
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);
    }
}

示例 3:带超时和重试的异步操作

Python 版本
import asyncio
import aiohttp
from typing import Optional

async def fetch_with_retry(
    session: aiohttp.ClientSession,
    url: str,
    max_retries: int = 3,
    timeout: float = 5.0
) -> Optional[dict]:
    """带重试和超时的异步请求"""
    
    for attempt in range(max_retries):
        try:
            # 设置超时
            async with asyncio.timeout(timeout):
                async with session.get(url) as response:
                    if response.status == 200:
                        return await response.json()
                    else:
                        raise Exception(f"HTTP {response.status}")
        
        except asyncio.TimeoutError:
            print(f"尝试 {attempt + 1}/{max_retries}: 请求超时")
        
        except Exception as e:
            print(f"尝试 {attempt + 1}/{max_retries}: 失败 - {e}")
        
        # 指数退避
        if attempt < max_retries - 1:
            wait_time = 2 ** attempt
            print(f"等待 {wait_time} 秒后重试...")
            await asyncio.sleep(wait_time)
    
    print("所有重试失败")
    return None

async def main():
    async with aiohttp.ClientSession() as session:
        result = await fetch_with_retry(
            session,
            "https://api.example.com/data",
            max_retries=3,
            timeout=5.0
        )
        
        if result:
            print(f"成功获取数据:{result}")
        else:
            print("最终失败")

asyncio.run(main())
Java 版本
import java.net.http.*;
import java.time.Duration;
import java.util.concurrent.*;

public class RetryWithTimeout {
    
    private final HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build();
    
    private final ExecutorService executor = Executors.newCachedThreadPool();
    
    public CompletableFuture<String> fetchWithRetry(
        String url,
        int maxRetries,
        long timeoutMs
    ) {
        return fetchWithRetryInternal(url, maxRetries, timeoutMs, 0);
    }
    
    private CompletableFuture<String> fetchWithRetryInternal(
        String url,
        int maxRetries,
        long timeoutMs,
        int attempt
    ) {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .timeout(Duration.ofMillis(timeoutMs))
            .GET()
            .build();
        
        return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .exceptionallyCompose(ex -> {
                // 如果失败,判断是否需要重试
                if (attempt < maxRetries - 1) {
                    System.out.printf("尝试 %d/%d: 失败 - %s%n", 
                        attempt + 1, maxRetries, ex.getMessage());
                    
                    // 指数退避
                    long waitTime = (long) Math.pow(2, attempt) * 1000;
                    System.out.println("等待 " + waitTime + "ms 后重试...");
                    
                    return CompletableFuture.completedFuture(null)
                        .thenComposeAsync(v -> {
                            try {
                                Thread.sleep(waitTime);
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                            }
                            return null;
                        }, executor)
                        .thenCompose(v -> fetchWithRetryInternal(
                            url, maxRetries, timeoutMs, attempt + 1
                        ));
                } else {
                    System.out.println("所有重试失败");
                    return CompletableFuture.failedFuture(ex);
                }
            });
    }
    
    public void run() {
        fetchWithRetry("https://api.example.com/data", 3, 5000)
            .thenAccept(result -> {
                if (result != null) {
                    System.out.println("成功获取数据:" + result);
                } else {
                    System.out.println("最终失败");
                }
            })
            .join();
    }
}

5️⃣ 常见陷阱与最佳实践

陷阱 1:在异步函数中使用阻塞调用

# ❌ 错误示例
async def bad_example():
    result = await some_async_call()
    
    # 阻塞调用!会卡住整个事件循环
    time.sleep(5)  # ❌ 不要用这个!
    
    return result

# ✅ 正确示例
async def good_example():
    result = await some_async_call()
    
    # 非阻塞等待
    await asyncio.sleep(5)  # ✅ 用这个!
    
    return result

Java 对比:

// ❌ Java 中的类似问题
public CompletableFuture<String> badExample() {
    return CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(5000);  // 阻塞线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "结果";
    });
}

// ✅ Java 改进版
public CompletableFuture<String> goodExample() {
    return CompletableFuture.supplyAsync(() -> {
        return "结果";
    }).thenApplyAsync(result -> {
        // 延迟处理,但不阻塞
        return delayedResult();
    });
}

陷阱 2:忘记使用 await

# ❌ 错误示例
async def forget_await():
    task = asyncio.create_task(some_async_call())
    # 忘记 await,直接返回 task 对象
    return task  # ❌ 返回的是 Coroutine 对象,不是结果!

# ✅ 正确示例
async def remember_await():
    task = asyncio.create_task(some_async_call())
    result = await task  # ✅ 等待结果
    return result

# 或者更简洁
async def concise_version():
    return await some_async_call()

陷阱 3:异常处理不当

# ❌ 错误示例
async def bad_error_handling():
    try:
        result = await risky_operation()
    except Exception as e:
        print(f"出错了:{e}")
        # 没有重新抛出或返回错误
        return None  # ❌ 吞掉异常,上层无法感知
    
    return result

# ✅ 正确示例
async def good_error_handling():
    try:
        result = await risky_operation()
        return result
    except Exception as e:
        print(f"出错了:{e}")
        raise  # ✅ 重新抛出,让上层决定如何处理

# 或者返回明确的错误类型
from typing import Optional, Tuple

async def explicit_error_handling() -> Tuple[bool, Optional[str]]:
    """返回 (成功标志,结果/错误信息)"""
    try:
        result = await risky_operation()
        return True, result
    except Exception as e:
        return False, str(e)

最佳实践 1:使用 asyncio.gather() 并发执行独立任务

# ✅ 推荐做法
async def fetch_all_data():
    # 三个独立的 IO 操作
    user_task = fetch_users()
    post_task = fetch_posts()
    comment_task = fetch_comments()
    
    # 并发执行
    users, posts, comments = await asyncio.gather(
        user_task, post_task, comment_task,
        return_exceptions=True  # ✅ 即使一个失败,其他也能继续
    )
    
    return users, posts, comments

最佳实践 2:使用 Semaphore 限制并发数

# ✅ 防止过多并发连接压垮服务器
async def fetch_with_limit(urls, max_concurrent=5):
    semaphore = asyncio.Semaphore(max_concurrent)
    
    async def fetch_one(url):
        async with semaphore:  # 限制并发数
            return await fetch_url(url)
    
    tasks = [fetch_one(url) for url in urls]
    return await asyncio.gather(*tasks)

Java 对比:

// Java 使用 Semaphore
Semaphore semaphore = new Semaphore(5);

public CompletableFuture<String> fetchWithLimit(String url) {
    try {
        semaphore.acquire();  // 获取许可
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    
    try {
        return fetchUrl(url)
            .whenComplete((result, ex) -> semaphore.release());  // 释放许可
    } catch (Exception e) {
        semaphore.release();
        throw e;
    }
}

最佳实践 3:使用上下文管理器处理资源

# ✅ 确保资源正确释放
async def process_file(filename):
    async with aiofiles.open(filename, 'r') as f:  # 自动关闭
        content = await f.read()
        return content

# 自定义异步上下文管理器
class AsyncResource:
    async def __aenter__(self):
        await self.connect()
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

async def use_resource():
    async with AsyncResource() as resource:
        await resource.do_something()
    # 自动调用 __aexit__,即使发生异常

Java 对比:

// Java try-with-resources(类似 Python 上下文管理器)
try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.readLine();
} catch (IOException e) {
    e.printStackTrace();
}
// 自动关闭资源

6️⃣ 总结对比表

核心概念对照

Python 概念Java 对应物说明
async defCompletableFuture<T>异步方法定义
await.thenApply() / .join()等待异步结果
asyncio.create_task()CompletableFuture.supplyAsync()创建异步任务
asyncio.gather()CompletableFuture.allOf()等待所有任务完成
asyncio.QueueBlockingQueue异步队列
asyncio.LockReentrantLock异步锁
asyncio.SemaphoreSemaphore信号量
asyncio.run(main())ExecutorService启动异步程序
aiohttpHttpClient (Java 11+)异步 HTTP 客户端
async withtry-with-resources异步上下文管理器

并发模型对比

特性Python asyncioJava 线程池
线程数量单线程(主线程)多线程
调度方式协作式(任务主动让出)抢占式(OS 调度)
内存占用低(KB 级 per coroutine)高(MB 级 per thread)
最大并发百万级千级
适用场景IO 密集型CPU + IO 密集型
学习曲线中等(需理解 async/await)较陡(需理解线程安全)

性能对比

场景:1000 个 HTTP 请求

Python asyncio:
├─ 启动时间:~0.1s
├─ 内存占用:~50MB
├─ 并发数:1000(单线程)
└─ 总耗时:~10s

Java 线程池:
├─ 启动时间:~0.5s
├─ 内存占用:~500MB
├─ 并发数:~100(受线程池大小限制)
└─ 总耗时:~100s(分批执行)

结论:IO 密集型场景,Python asyncio 优势明显

🎯 给 Java 开发者的建议

1. 心态转变

  • ❌ 不要想"这会阻塞吗?"
  • ✅ 要想"这是在等待 IO 吗?如果是,就用 await"

2. 代码风格

# ❌ Java 风格的 Python 代码
def fetch_data():
    future = asyncio.create_task(api_call())
    # ... 做其他事
    result = future.result()  # 阻塞等待
    return result

# ✅ Pythonic 风格
async def fetch_data():
    result = await api_call()
    return result

3. 调试技巧

# 添加日志查看执行顺序
async def debug_example():
    print(f"[{asyncio.get_event_loop().time():.2f}] 开始")
    
    result = await some_call()
    
    print(f"[{asyncio.get_event_loop().time():.2f}] 完成:{result}")
    return result

4. 测试异步代码

import pytest

# ✅ 测试异步函数
@pytest.mark.asyncio
async def test_async_function():
    result = await my_async_function()
    assert result == expected_value

# 或在测试中运行事件循环
def test_with_loop():
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(my_async_function())
    assert result == expected_value

📚 推荐学习资源

Python 异步编程

  • 📖 官方文档:asyncio
  • 📖 书籍:《Python Asyncio 并发编程》
  • 🎥 视频:David Beazley - Asyncio Demystified

Java 对比学习

  • 📖 《Java 并发编程实战》
  • 📖 《Java 8 函数式编程》
  • 📖 Project Loom(虚拟线程,类似 Python 协程)

✅ 关键要点回顾

  1. async/await 不是阻塞:是暂停当前任务,释放线程给其他任务
  2. Event Loop 是核心:单线程调度百万级并发
  3. await 必须在 async 函数内:不能在同步函数中直接 await
  4. 并发用 gather():独立任务用 asyncio.gather() 并发执行
  5. 避免阻塞调用:用 await asyncio.sleep() 替代 time.sleep()
  6. 异常处理要谨慎:要么重新抛出,要么明确返回错误
  7. 资源管理用 async with:确保异步资源正确释放

作者:Alioo Agent Team
最后更新:2026-03-23
基于 Python 3.13 + Java 17/21

python零基础入门到精通,python入门到精通教程 坚持到了这儿,恭喜你,表示你有做开发的潜力,其实我想说的上面的内容还是刚刚开始,刚开始大家不需要多么精通了解这些内容,除了Python方面的知识,每个部分掌握一点儿能进行基本开发就好,主要是不断练习,让自己跳出「舒适区」,进入「学习区」,但是又不进入「恐慌区」,不断给自己「喂招」。上述这份完整版的Python全套学习资料已经上传CSDN官方,朋友们如果需要可以扫描下方二维码免费获取【保证100%免费】 阅读详情

相关推荐

Python入门实战:Python的并发编程

1.背景介绍 Python是一种强大的编程语言,它具有简洁的语法和易于学习。在现实生活中,我们经常需要编写并发程序来处理大量的数据和任务。Python的并发编程是一种高效的编程方法,可以让我们的程序更快地执行任务,从而提高效率。 在本文中,我们将讨论Python的并发编程的核心概念、算法原理、具体操作步骤、数学模型公式、代码实例以及未来发

AI架构师小马 366

Pycharm及python安装详细教程

首先我们来安装python 1、首先进入网站下载:点击打开链接(或自己输入网址https://www.python.org/downloads/),进入之后如下图,选择图中红色圈中区域进行下载。 2、下载完成后如下图所示 3、双击exe文件进行安装,如下图,并按照圈中区域进行设置,切记要勾选打钩的框,然后再点击Customize install

陌上行走的博客 76万+

Python 中的 util 库安装详解:从 Java 工具库的视角看 Python 工具集

在上一篇文章中,我们探讨了Python 实现数字按照三角形排列,并通过 Python 和 Java 两种语言的不同实现,深入剖析了算法的实现细节。数字排列是一个典型的算法练习,而在实际的项目开发中,除了算法之外,我们常常需要借助工具库来简化和加速开发过程。在 Python 中,util库是一个常用的工具集合,可以帮助开发者快速完成一些常见的编程任务。工具库在各种编程语言中都扮演着重要角色。例如,在 Java 中,我们有java.util包,其中包含了许多实用的类,如集合框架、日期和时间管理等。

喵手的博客 1443

Python入门教程(全网最详细),零基础入门到精通,从看这一篇开始!

一.初聊Python在学习Python之前,你不要担心自己没基础或“脑子笨”,我始终认为,只要你想学并为之努力,就能学好,就能用Python去做很多事情。在这个喧嚣的时代,很多技术或概念会不断兴起,我希望你能沉下心来去学习,不要急于求成,一步一个脚印。当你把某个技术学好、学精后,还是能做一些事情的,甚至能找到喜欢的工作或完成实践项目。程序语言没有最好,只有最适合。作为一名初学者,我非常推荐你学习Python,为啥?

m0_59236602的博客 11万+

深入解析MOSFET结电容与分布参数:Cgd、Cgs、Cds与Ciss、Crss、Coss的关系与应用

本文深入解析了MOSFET结电容Cgd、Cgs、Cds及其等效参数Ciss、Crss、Coss对开关性能的影响。文章详细阐述了米勒电容Cgd如何导致开关损耗与振荡,并提供了基于电容参数的高频电路选型、驱动设计及PCB布局优化等实战指南,帮助工程师解决开关电源与电机驱动中的常见问题。

weixin_29240711的博客 1354

ESP32 DMX512与RDM协议栈开发指南

DMX512-A是专业灯光控制领域广泛采用的串行通信标准,基于RS-485物理层实现确定性单向数据传输;RDM(Remote Device Management)则在其基础上扩展双向、可寻址、可配置的智能管理能力,满足现代舞台设备远程固件升级、自动发现与参数配置需求。二者共用同一总线但时序与帧结构严格隔离,对硬件定时精度、中断响应延迟及电气隔离提出极高要求。在嵌入式实践中,ESP32凭借Wi-Fi/蓝牙连接能力与丰富外设资源,成为构建低成本智能DMX节点的理想平台。esp_dmx协议栈正是面向该场景的高性能

weixin_34945060的博客 321

极简 Python 语言教程:从 Java 开发者视角入门实战

本文为Java开发者提供了快速掌握Python核心语法的教程。通过对比两种语言的异同点,帮助开发者高效学习Python。内容涵盖环境搭建、基础语法、数据类型、控制流、函数、面向对象、异常处理、文件操作、数据库访问和并发编程等核心概念,并配有对应的Java和Python代码示例。最后通过实战项目演示了如何用两种语言实现RESTful API服务。

果酱 の 博客 2177

Win11只读模式无法关闭的终极解决方案

通过以上方法,我们应该能够解决Windows 11中文件夹无法取消只读状态的问题。如果问题仍然存在,请确保你的账户具有足够的权限来修改文件夹属性,并考虑是否有其他安全软件或策略阻止了权限更改。在操作过程中,请务必小心谨慎,避免误操作导致数据丢失或系统损坏。希望本文能够帮助到大家!

mmoo_python的博客 1万+

为什么选择 Rust:从 Python/Java 开发者的视角

摘要: Rust作为现代系统级编程语言,凭借内存安全、零成本抽象和高性能等特性,吸引了Python/Java开发者的关注。对于Python开发者,Rust弥补了动态类型和解释执行的性能瓶颈,通过静态类型和编译优化提升效率,但需适应所有权模型和严格编译检查。对于Java开发者,Rust以无GC的确定性内存管理、编译时线程安全等优势,提供了更底层的控制能力,但需克服所有权和生命周期的学习曲线。两者可互补:Python/Rust混合开发(如PyO3)兼顾灵活性与性能;Java/Rust结合(如JNI)优化关键模块

油墨香^-^的博客 351

STM32_DAC

DAC(Digital-to-Analog Converter,数模转换器)是将数字信号转换为模拟信号的外设,广泛应用于音频输出、波形生成、电机控制等场景。STM32F407 系列芯片配备了 2 个 DAC 通道(DAC1 和 DAC2),支持 12 位分辨率,支持多种触发方式,可输出稳定的模拟电压。本文从 DAC 的基本原理出发,详细讲解 STM32F407 DAC 的配置方法、代码实现、波形生成以及实际应用案例,帮助你快速掌握 DAC 的使用技巧。

轩宇的博客 1245

Postman调试海康ISAPI接口全记录:从鉴权失败到成功修改设备名的踩坑指南

本文详细记录了使用Postman调试海康ISAPI接口的全过程,从鉴权失败到成功修改设备名的实战经验。涵盖Digest认证机制、XML请求体构造、常见错误排查及代码实现过渡,帮助开发者高效解决海康设备集成中的各种问题。

weixin_42620913的博客 675

Python系统学习计划(Java开发者视角)

用列表推导式+lambda实现Java Stream API的。:打破Java思维定式,建立Python动态语言认知框架。:精准选择Python优势战场,避开Java更适合场景。Python不需要Factory模式处理简单对象创建。:掌握Python独有武器库,解决Java笨重场景。🚀 第二阶段:核心特性精炼(Day 6-10)动态类型不是缺陷而是工具,善用。协议编程 vs 接口继承。拓展一下,先上计划!问题不大,坚持学习!

weixin_46302418的博客 1031

【Claude Code 源码解析教程】第4章:QueryEngine 查询引擎

本章深入解析 Claude Code 的核心引擎——QueryEngine,它是整个对话系统的"心脏",负责管理会话状态、消息处理流程和多轮对话支持。

rengang66的博客 273

Python 基础入门:Java 开发者视角

Python与Java核心概念差异对比 摘要 本文面向有Java经验的开发者,通过对比两种语言的核心概念差异,帮助快速建立Python的正确思维模型。主要内容包括: 环境与工具链:Python使用VS Code开发、pip/poetry管理依赖,强调虚拟环境隔离 核心概念对比: 类型系统:Java是静态强类型,Python是动态强类型 执行方式:Java需要编译,Python直接解释执行 入口点:Java强制main方法,Python通过if __name__ == "__main__":实现可选入口 模块

m0_54123999的博客 268

14、微电网控制方法与建模分析

本文详细探讨了微电网的控制方法与建模分析,包括逆变器的小信号状态空间模型、网络模型、负载模型及其组合形成的完整微电网模型。通过对系统特征值和灵敏度因子的分析,揭示了不同模式与系统参数之间的关系。文章还提出了多个研究问题,如岛式系统控制器设计、风力发电控制、并网变换器控制等,为微电网的稳定性分析和优化控制提供了理论支持和实践方向。

elastic6hunter的博客 128

【FISCO BCOS】二十、多机部署区块链

实际开发中,为了满足高可用性和高容错性的需求,往往会采用多级部署区块链的方式,今天介绍一下FISCO BCOS的多机部署流程。

naihe_fish的博客 3656

Python 变量全解:从入门到精通 —— Java 开发者视角下的变量机制、内存模型与最佳实践

在 Python 中,赋值语句x = value的本质是将名称x绑定到value所代表的对象上。这由 Python 的命名空间(namespace)机制实现。创建int(42)对象;将名称x绑定到该对象;将名称y也绑定到同一对象。可通过id()print(id(x)) # 输出:140712345678900print(id(y)) # 输出:140712345678900 → 相同!✅小贴士id(obj)返回对象的唯一标识(通常为内存地址),是判断两个变量是否指向同一对象的可靠方法。

吾为热爱计科,致力于知识分享的践行者,此博客是我在这条道路上留下的足迹。 653

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

【Go入门篇】第一章:从 Java/Python 开发者的视角入门go语言

Go 语言(Golang)是由 Google 开发的一门静态强类型、编译型的编程语言,凭借其简洁性、高效性和强大的并发支持,成为后端开发、云计算和微服务的热门选择。本篇文章将带你快速入门 Go 语言,了解其基础概念,并通过 Java/Python 的对比帮助理解。

分享技术,记录思考和感悟 1190

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Python 流水账(Java 开发者视角)

Python与Java核心差异摘要(面向AI应用开发) 本文对比Java与Python在语法、类型系统、异步编程等关键差异,帮助Java开发者快速掌握Python核心特性。主要内容: 动态类型与鸭子类型:Python变量无固定类型,依赖运行时检查,通过协议(Protocol)实现类似Java接口的灵活性 类型提示与校验:Type Hints提供IDE支持,需配合mypy/Pydantic实现静态检查与运行时校验 AI开发常用范式:asyncio处理LLM并发调用,@dataclass替代DTO,Pydant

wuhui2100的博客 403

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java 开发者“优雅”转战 Python:FastAPI 是 Spring Boot 的平替吗?

文章摘要:Java开发者Evan分享了对Python框架FastAPI的探索心得。通过对比SpringBoot和FastAPI,指出后者在快速开发API、自动文档生成和异步性能方面的优势,但承认SpringBoot在企业级生态上更成熟。文章分析了Python微服务生态的现状,强调中间件可复用性,并为Java开发者规划了Python学习路径。最终结论是两种技术应互补使用,建议开发者根据场景选择合适的工具,而非对立比较。(149字)

2503_93374004的博客 963

Java 转 Python 速成指南:Java 视角下常用的 Python 特性

本文为Java开发者提供了快速掌握Python高阶特性的指南,重点针对LLM业务场景。主要内容包括:1)使用Pydantic进行数据校验和结构化(类似Java的POJO);2)利用Asyncio处理IO密集型并发任务(替代Java线程池);3)通过Generators实现流式响应处理;4)使用装饰器实现AOP切面编程(如API自动重试)。文章采用Java与Python对比的方式,帮助开发者快速理解Python在大模型开发中的最佳实践,如异步编程、类型注解和装饰器等核心特性。

823

Python与Java核心差异深度解析:从动态类型到PEP 8规范(Java开发者视角

Python与Java在设计哲学上各有侧重。Python以其简洁的语法、动态类型和快速开发周期吸引了大量开发者,特别是在数据科学、人工智能、Web开发等领域。而Java则凭借其静态类型、编译时检查、强大的生态系统和跨平台能力,在企业级应用、大型系统和Android开发中占据主导地位。理解这些根本差异,有助于开发者根据项目需求、团队技能和性能考量,做出更明智的技术选型。两者并非绝对的优劣之分,而是不同场景下的不同适用性。

冷脸萌萌的技术实践 1292

从Java开发者视角看Python为什么你应该学习这门脚本语言

Python以简洁著称,相比Java的冗长代码,Python能用更少的行数完成相同功能。与Java的静态类型系统不同,Python的动态类型让你无需声明变量类型。然而,学习Python这门动态脚本语言将为你的技术栈带来全新的视角和优势。掌握Python不仅能提升你的开发效率,还能扩展你的技术视野,为应对多样化项目需求做好准备。你已有的编程概念(如循环、条件判断、面向对象)都能直接应用,只需适应新的语法和动态类型系统。这种多范式方法能拓宽你的编程思维,帮助你以不同方式解决问题,提升代码设计和架构能力。

XYfBDUwA的博客 247

Java开发者眼中的Python为何值得学习与借鉴

在软件开发领域,Java开发者拥有严谨的工程思维和架构设计能力,而Python作为一门动态语言,其设计哲学和编程范式与Java形成鲜明对比。3. 列表推导式的数据处理:Python的[item for item in list if condition]语法展示了声明式编程的魅力,这种思想可以应用于Java Stream API的使用中。2. 上下文管理器的资源管理:Python的with语句通过上下文管理器实现资源的自动释放,这种模式对Java的try-with-resources语法有重要影响。

frcrvtSt的博客 318
上一篇: 大模型的“推理能力” vs. AgentScope 框架的“推理循环”:你分清楚了吗?
下一篇: 投资笔记-市盈率、市净率、股息率
明月(Alioo)
博客等级 码龄18年 267粉丝 207原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月(Alioo)

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址