移动端六大语言速记:第9部分 - 并发与多线程
移动端六大语言速记:第9部分 - 并发与多线程
本文将对比Java、Kotlin、Flutter(Dart)、Python、ArkTS和Swift这六种移动端开发语言在并发与多线程方面的特性,帮助开发者理解和掌握各语言的并发编程机制。
9. 并发与多线程
9.1 线程与进程
各语言线程与进程的创建和管理方式对比:
语言 | 线程创建方式 | 进程创建方式 | 线程池支持 | 线程生命周期管理 |
---|---|---|---|---|
Java | Thread 类, Runnable 接口 |
ProcessBuilder |
ExecutorService |
状态管理,中断机制 |
Kotlin | 继承Java线程模型,协程 | 继承Java进程模型 | ExecutorService ,协程调度器 |
协程作用域,Job管理 |
Dart | Isolate (类似进程) |
不直接支持 | 无原生线程池 | Isolate控制,Stream |
Python | threading 模块 |
multiprocessing 模块 |
concurrent.futures |
守护线程,join方法 |
ArkTS | Worker (类似Web Worker) |
不直接支持 | 不直接支持 | Worker生命周期管理 |
Swift | Thread , Operation |
Process |
OperationQueue |
取消操作,依赖管理 |
示例对比
Java:
// 使用Thread类创建线程
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程1运行中...");
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1完成");
}
});
thread1.start(); // 启动线程
// 使用lambda表达式简化
Thread thread2 = new Thread(() -> {
System.out.println("线程2运行中...");
System.out.println("线程2完成");
});
thread2.start();
// 线程池示例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executor = Executors.newFixedThreadPool(5); // 创建固定大小为5的线程池
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.execute(() -> {
System.out.println("任务" + taskId + "由线程" + Thread.currentThread().getName() + "执行");
});
}
executor.shutdown(); // 关闭线程池
// 进程创建示例
try {
ProcessBuilder processBuilder = new ProcessBuilder("notepad.exe");
Process process = processBuilder.start();
// 等待进程结束
int exitCode = process.waitFor();
System.out.println("进程退出码: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
Kotlin:
// 使用Thread类创建线程
val thread1 = Thread {
println("线程1运行中...")
Thread.sleep(1000) // 休眠1秒
println("线程1完成")
}
thread1.start() // 启动线程
// 使用协程
import kotlinx.coroutines.*
// 在主线程中启动协程
fun main() = runBlocking {
// 创建一个阻塞协程,通常用于main函数
launch {
// 在当前协程作用域中启动新协程
println("协程1运行中...")
delay(1000) // 非阻塞休眠1秒
println("协程1完成")
}
launch {
println("协程2运行中...")
delay(500)
println("协程2完成")
}
println("主协程等待子协程完成")
} // runBlocking会等待内部所有协程完成
// 协程作用域和取消示例
val job = GlobalScope.launch {
try {
println("长时间运行的任务开始")
repeat(1000) {
i ->
println("任务进度: $i")
delay(100)
}
} catch (e: CancellationException) {
println("任务被取消")
} finally {
println("清理资源")
}
}
// 5秒后取消任务
delay(5000)
job.cancel()
job.join() // 等待任务完成取消
// 使用协程调度器
val dispatcher = Dispatchers.IO // IO密集型任务的调度器
val job2 = GlobalScope.launch(dispatcher) {
// 在IO线程池中执行
println("在IO线程池中执行: ${
Thread.currentThread().name}")
}
Dart:
// Dart使用Isolate而非线程
import 'dart:isolate';
import 'dart:async';
// 在新Isolate中执行的函数
void isolateFunction(SendPort sendPort) {
sendPort.send('Hello from isolate!');
}
// 创建和使用Isolate
Future<void> createIsolate() async {
// 创建通信通道
final receivePort = ReceivePort();
// 启动新的Isolate
await Isolate.spawn(isolateFunction, receivePort.sendPort);
// 接收消息
receivePort.listen((message) {
print('收到消息: $message');
receivePort.close(); // 关闭通信端口
});
}
// 在Flutter中使用compute函数在后台Isolate中执行计算密集型任务
import 'package:flutter/foundation.dart';
// 计算密集型函数
int computeFactorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// 在UI中调用
void calculateInBackground() async {
final result = await compute(computeFactorial, 20);
print('20的阶乘是: $result');
}
Python:
# 使用threading模块创建线程
import threading
import time
def task(name, delay):
print(f"{
name}开始运行")
time.sleep(delay) # 模拟耗时操作
print(f"{
name}完成")
# 创建线程
thread1 = threading.Thread(target=task, args=("线程1", 2))
thread2 = threading.Thread(target=task, args=("线程2", 1))
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
print("所有线程完成")
# 使用线程池
from concurrent.futures import ThreadPoolExecutor
def worker(num):
print(f"任务{
num}开始")
time.sleep(1)
return f"任务{
num}的结果"
# 创建线程池
with ThreadPoolExecutor(max_workers=3) as executor:
# 提交任务并获取Future对象
futures = [executor.submit(worker, i) for i in range(5)]
# 获取结果
for future in futures:
print(future.result())
# 使用multiprocessing模块创建进程
from multiprocessing import Process
def process_task():
print(f"进程{
Process.current().pid}运行中")
time.sleep(2)
print(f"进程{
Process.current().pid}完成")
if __name__ == "__main__": # 在Windows上必须有这个保护
# 创建进程
process = Process(target=process_task)
process.start()
process.join()
print("主进程继续执行")
ArkTS:
// 使用Worker在后台线程执行任务
import worker from '@ohos.worker';
// 创建Worker
function createWorker() {
// 创建Worker实例,指定Worker脚本文件路径
const workerInstance = new worker.Worker('workers/worker.ts');
// 监听Worker消息
workerInstance.onmessage = (message) => {
console.log(`从Worker收到消息: ${
message.data}`);
};
// 监听Worker错误
workerInstance.onerror = (error) => {
console.error(`Worker错误: ${
error.message}`);
};
// 向Worker发送消息
workerInstance.postMessage('开始计算');
// 一段时间后终止Worker
setTimeout(() => {
workerInstance.terminate();
console.log('Worker已终止');
}, 5000);
}
// worker.ts文件内容
// 接收主线程消息
onmessage = (message) => {
console.log(`Worker收到消息: ${
message.data}`);
// 执行耗时计算
let result = 0;
for (let i = 0; i < 10000000; i++) {
result += i;
}
// 向主线程发送结果
postMessage(`计算结果: ${
result}`);
};
Swift:
// 使用Thread创建线程
import Foundation
// 创建线程
let thread = Thread {
print("线程运行中...")
Thread.sleep(forTimeInterval: 1) // 休眠1秒
print("线程完成")
}
thread.start() // 启动线程
// 使用Operation和OperationQueue
import Foundation
// 创建自定义Operation
class CustomOperation: Operation {
let taskID: Int
init(taskID: Int) {
self.taskID = taskID
super.init()
}
override func main() {
// 检查是否被取消
if isCancelled {
return
}
print("任务\(taskID)开始执行")
// 模拟耗时操作
Thread.sleep(forTimeInterval: 2)
print("任务\(taskID)完成")
}
}
// 创建OperationQueue
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 2 // 设置最大并发数
// 添加操作到队列
for i in 1...5 {
let operation = CustomOperation(taskID: i)
queue.addOperation(operation)
}
// 添加操作完成块
let completionOperation = BlockOperation {
print("所有任务完成")
}
// 设置依赖关系,completionOperation会在队列中所有操作完成后执行
for operation in queue.operations {
completionOperation.addDependency(operation)
}
queue.addOperation(completionOperation)
// 使用Process创建进程
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = ["ls", "-la"]
let pipe = Pipe()
process.standardOutput = pipe
try {
try process.run()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
print(output)
}
} catch {
print("Error: \(error)")
}
9.2 同步机制
各语言同步机制的对比:
语言 | 互斥锁 | 读写锁 | 信号量 | 条件变量 | 原子操作 |
---|---|---|---|---|---|
Java | synchronized , Lock |
ReadWriteLock |
Semaphore |
Condition |
AtomicInteger 等 |
Kotlin | 继承Java同步机制,协程互斥 | 继承Java读写锁 | 继承Java信号量 | 继承Java条件变量 | 继承Java原子类 |
Dart | Lock (package:synchronized) |
无原生支持 | 无原生支持 | 无原生支持 | 无原生支持 |
Python | Lock , RLock |
无原生支持 | Semaphore , BoundedSemaphore |
Condition |
无原生支持 |
ArkTS | 不直接支持,通过Worker通信 | 不直接支持 | 不直接支持 | 不直接支持 | 不直接支持 |
Swift | NSLock , os_unfair_lock |
pthread_rwlock_t |
DispatchSemaphore |
NSCondition |
原子操作函数 |
示例对比
Java:
// 使用synchronized关键字
class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// 使用显式锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BankAccount {
private double balance;
private final Lock lock = new ReentrantLock();
public void deposit(double amount) {
lock.lock();
try {
balance += amount;
} finally {
lock