package com.sw.platecabinet.utils import android.os.Handler import android.os.Looper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import kotlin.coroutines.CoroutineContext /** * 多功能线程工具类 * 结合协程、Handler和线程池实现线程切换 */ object ThreadUtils : CoroutineScope { // 主线程Handler private val mainHandler by lazy { Handler(Looper.getMainLooper()) } // 后台线程池(IO密集型任务) private val ioThreadPool: ExecutorService by lazy { Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2) } // CPU密集型线程池 private val cpuThreadPool: ExecutorService by lazy { Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) } // 协程Job管理 private val job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job // ========== Handler相关方法 ========== /** * 在主线程执行任务 * @param delayMillis 延迟时间(毫秒) */ fun runOnUiThread(delayMillis: Long = 0, block: () -> Unit) { if (delayMillis > 0) { mainHandler.postDelayed(block, delayMillis) } else { if (isOnMainThread()) { block() } else { mainHandler.post(block) } } } /** * 移除主线程任务 */ fun removeUiThreadTask(block: () -> Unit) { mainHandler.removeCallbacks(block) } // ========== 线程池相关方法 ========== /** * 在IO线程执行任务 */ fun runOnIoThread(block: () -> Unit) { ioThreadPool.execute(block) } /** * 在CPU计算线程执行任务 */ fun runOnCpuThread(block: () -> Unit) { cpuThreadPool.execute(block) } // ========== 协程相关方法 ========== /** * 启动协程(默认在主线程) */ fun launch(block: suspend CoroutineScope.() -> Unit): Job { return launch(coroutineContext, block = block) } /** * 在IO线程启动协程 */ fun launchOnIo(block: suspend CoroutineScope.() -> Unit): Job { return launch(Dispatchers.IO, block = block) } /** * 切换到主线程(协程环境) */ suspend fun switchToMain(block: suspend CoroutineScope.() -> T): T { return withContext(Dispatchers.Main, block) } /** * 切换到IO线程(协程环境) */ suspend fun switchToIo(block: suspend CoroutineScope.() -> T): T { return withContext(Dispatchers.IO, block) } /** * 是否在主线程 */ fun isOnMainThread(): Boolean { return Looper.myLooper() == Looper.getMainLooper() } /** * 释放资源 */ fun release() { job.cancel() ioThreadPool.shutdown() cpuThreadPool.shutdown() } }