Skip to content

并行构建

并行构建允许 Gradle 同时执行多个没有依赖关系的任务,在多项目构建和多核机器上效果显著。

启用并行构建

bash
# 单次启用
./gradlew build --parallel

# 限制并行数量
./gradlew build --parallel --max-workers=4
properties
# gradle.properties(永久启用)
org.gradle.parallel=true
org.gradle.workers.max=8  # 最大并发工作线程数(默认=CPU 核心数)

多项目并行

project
├── core          ← 独立,可并行
├── utils         ← 独立,可并行
├── service-a     ← 依赖 core,等 core 完成
└── service-b     ← 依赖 core,等 core 完成

并行时序:
time →
[core   ████████]
[utils  ██████  ]
                [service-a ████]
                [service-b ████]

Worker API(任务内并行)

Worker API 允许在单个任务内部并行执行工作:

kotlin
abstract class ProcessFilesTask @Inject constructor(
    private val workerExecutor: WorkerExecutor
) : DefaultTask() {
    
    @get:InputDirectory
    abstract val sourceDir: DirectoryProperty
    
    @get:OutputDirectory
    abstract val outputDir: DirectoryProperty
    
    @TaskAction
    fun process() {
        val queue = workerExecutor.classLoaderIsolation()
        
        sourceDir.get().asFile.walkTopDown()
            .filter { it.isFile }
            .forEach { file ->
                // 每个文件在独立线程中处理
                queue.submit(ProcessFileWorkAction::class) {
                    inputFile.set(file)
                    outputFile.set(outputDir.file(file.name))
                }
            }
    }
}

interface ProcessFileParameters : WorkParameters {
    val inputFile: RegularFileProperty
    val outputFile: RegularFileProperty
}

abstract class ProcessFileWorkAction : WorkAction<ProcessFileParameters> {
    override fun execute() {
        val content = parameters.inputFile.get().asFile.readText()
        parameters.outputFile.get().asFile.writeText(content.uppercase())
    }
}

测试并行执行

kotlin
tasks.named<Test>("test") {
    // JVM 级别:多个测试 JVM 并行
    maxParallelForks = Runtime.getRuntime().availableProcessors() / 2
    
    // 进程内:JUnit 5 线程级并行
    systemProperty("junit.jupiter.execution.parallel.enabled", "true")
    systemProperty("junit.jupiter.execution.parallel.config.strategy", "dynamic")
}

下一步