package com.mogo.cloud.network

import java.util.concurrent.*

object CustomThreadPool {
    private const val CORE_POOL_SIZE = 5 // 核心线程数
    private const val MAXIMUM_POOL_SIZE = 10 // 最大线程数
    private const val KEEP_ALIVE_TIME = 1L // 空闲线程存活时间（单位：秒）
    private const val QUEUE_CAPACITY = 100 // 队列容量

    private val workQueue = LinkedBlockingQueue<Runnable>(QUEUE_CAPACITY) // 任务队列

    private fun createThreadPool(): ExecutorService {
        return ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            workQueue,
            NamedThreadFactory("OkHttp Dispatcher"),
            ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        )
    }

    fun getThreadPool(): ExecutorService {
        return createThreadPool()
    }

    // 自定义线程工厂，为线程命名
    private class NamedThreadFactory(private val namePrefix: String) : ThreadFactory {
        private var threadId = 1

        override fun newThread(runnable: Runnable): Thread {
            val thread = Thread(runnable, "$namePrefix-#$threadId")
            thread.isDaemon = true
            threadId++
            return thread
        }
    }
}