⚙️ 什么是并发编程?
并发编程是通过同时执行多个任务提升程序性能的技术。常见实现方式包括:
- 多线程(Thread)
- 异步编程(Async)
- 协程(Coroutine)
- 并行计算(Parallel)
📌 本文提供多种编程语言的并发示例,点击🔗 并发编程基础概念可深入了解原理
📝 各语言并发实现示例
🐍 Python:多线程与异步
import threading
import asyncio
# 多线程示例
def thread_task(name):
print(f"线程 {name} 启动")
threading.Thread(target=asyncio.sleep, args=(1,)).start()
# 异步示例
async def async_task(name):
print(f"协程 {name} 启动")
await asyncio.sleep(1)
thread_task("Python_Thread")
asyncio.run(async_task("Python_Async"))
并发编程
🐘 Java:线程与并发工具
// 多线程示例
class ThreadExample extends Thread {
public void run() {
System.out.println("Java 线程执行中");
}
}
// 并发工具示例
import java.util.concurrent.CountDownLatch;
public class LatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println("Java 并发任务");
latch.countDown();
}).start();
}
latch.await();
}
}
多线程
🐱 Go:并发模型
package main
import (
"fmt"
"time"
)
// 并发函数
func worker(id int) {
fmt.Printf("Go 协程 %d 启动\n", id)
time.Sleep(time.Second)
fmt.Printf("Go 协程 %d 结束\n", id)
}
func main() {
for i := 0; i < 5; i++ {
go worker(i)
}
time.Sleep(time.Second * 2)
}
Go语言
📱 JavaScript:异步编程
// Promise 示例
Promise.resolve().then(() => {
console.log("JavaScript 异步任务");
});
// async/await 示例
async function asyncTask() {
console.log("async 函数执行中");
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("async 函数完成");
}
asyncTask();
JavaScript异步
📚 推荐学习路径
- 🔗 并发编程基础概念 - 理论入门
- 🔗 并发编程性能优化 - 高级技巧
- 🔗 分布式系统设计 - 扩展应用场景
🧠 图片关键词已根据技术主题自动生成,包含“并发编程”“多线程”“异步编程”等中英文词汇,符合内容安全规范