Android Runnable-执行代码后,线程进入睡眠状态,不会终止

发布于 2025-02-09 02:07:12 字数 754 浏览 3 评论 0原文

我正在创建一个线程池,用于在Android应用中的背景中运行操作。 以下是创建线程池并执行操作的代码。线程池只会仅创建一次,但多次调用函数,因此将多个可运行的可运行量提交给执行程序。

fun performOperation(){
    if(executorPool == null)
        executorPool = Executors.newCachedThreadPool()
    val runnable = Runnable{
                           //operations
                           }
    val future = executorPool!!.submit(runnable)
}

我正在使用cachedthreadpool。根据定义,它说:

创建一个线程池,该线程池可根据需要创建新线程,但是在可用时会重复使用先前构造的线程。这些池通常会提高执行许多短期异步任务的程序的性能。执行的呼叫如果可用,将重复使用先前构造的线程。如果没有现有线程可用,将创建一个新线程并添加到池中。尚未使用六十秒的线终止并从缓存中删除。

我的期望是一旦执行操作,我的可运行线程应在60秒后自动终止,但是当我在CPU Profiler中检查时,从此处生成的可运行的线程继续增加了时代性能()函数。 在CPU Profiler中,我可以看到可运行的线程在睡眠状态而不终止(处于死状态)。

我想在这里减少线程计数,请指导我如何继续或应该如何处理。

I am creating a thread pool for running operations in background in an android app.
Following is the code to create the thread pool and perform operations. Thread pool will be created only once but function gets called multiple times so multiple runnables are submitted to executor.

fun performOperation(){
    if(executorPool == null)
        executorPool = Executors.newCachedThreadPool()
    val runnable = Runnable{
                           //operations
                           }
    val future = executorPool!!.submit(runnable)
}

I am using cachedThreadPool. by definition it says:

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache.

My expectation is once the operations are executed, my runnable thread should be terminated automatically after 60 seconds, but when I check in CPU profiler, runnable threads generated from here keep on increasing the times performOperation() function is called.
In CPU profiler, I can see runnable threads going in sleeping state and not terminating(in Dead state).

I want to reduce the Thread count here, please guide me how should I proceed or how should I handle this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幻梦 2025-02-16 02:07:12

每次运行操作时,请尝试记录活动线程计数和线程池大小,以确保是否是问题。

这就是我这样做的方式,

class MainActivity : AppCompatActivity() {

    private var executorPool:ExecutorService? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        performOperation()

        var button = findViewById<Button>(R.id.button)

        button.setOnClickListener {

            val runnable = Runnable{
                Thread.sleep(1000)
                Log.e("msg","ok!")
                if (executorPool is ThreadPoolExecutor) {
                    Log.e("msg",(executorPool as ThreadPoolExecutor).poolSize.toString())
                }
            }

            val future = executorPool!!.submit(runnable)

        }


    }

    fun performOperation(){
        if(executorPool == null)
            executorPool = Executors.newCachedThreadPool()

    }
}

这是我的logcat

2022-06-20 12:58:36.572 12493-12526/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:36.572 12493-12526/com.example.testkotlin E/msg: 1
2022-06-20 12:58:38.699 12493-12526/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:38.699 12493-12526/com.example.testkotlin E/msg: 3
2022-06-20 12:58:38.867 12493-12529/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:38.867 12493-12529/com.example.testkotlin E/msg: 3
2022-06-20 12:58:39.055 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:39.055 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:58:43.394 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:43.394 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:59:20.868 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:59:20.868 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:59:44.221 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:59:44.221 12493-12530/com.example.testkotlin E/msg: 1

,您可以在1分钟的线程池大小为1后再次出现3

Try logging active thread count and thread pool size everytime you run an operation to be sure if that is the issue.

This is how I did it

class MainActivity : AppCompatActivity() {

    private var executorPool:ExecutorService? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        performOperation()

        var button = findViewById<Button>(R.id.button)

        button.setOnClickListener {

            val runnable = Runnable{
                Thread.sleep(1000)
                Log.e("msg","ok!")
                if (executorPool is ThreadPoolExecutor) {
                    Log.e("msg",(executorPool as ThreadPoolExecutor).poolSize.toString())
                }
            }

            val future = executorPool!!.submit(runnable)

        }


    }

    fun performOperation(){
        if(executorPool == null)
            executorPool = Executors.newCachedThreadPool()

    }
}

This is my logcat

2022-06-20 12:58:36.572 12493-12526/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:36.572 12493-12526/com.example.testkotlin E/msg: 1
2022-06-20 12:58:38.699 12493-12526/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:38.699 12493-12526/com.example.testkotlin E/msg: 3
2022-06-20 12:58:38.867 12493-12529/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:38.867 12493-12529/com.example.testkotlin E/msg: 3
2022-06-20 12:58:39.055 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:39.055 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:58:43.394 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:58:43.394 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:59:20.868 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:59:20.868 12493-12530/com.example.testkotlin E/msg: 3
2022-06-20 12:59:44.221 12493-12530/com.example.testkotlin E/msg: ok!
2022-06-20 12:59:44.221 12493-12530/com.example.testkotlin E/msg: 1

Here you can see after 1 minute thread pool size is 1 again after going upto 3

烟─花易冷 2025-02-16 02:07:12

您曾经尝试过Kotlin Coroutines吗?
它更快,您不需要使用池。
coroutines basics

Android包括用于片段工作的范围
ViewModelScope
您也可以使用调度员创建范围 coroutinescope(dispatchers.io)或在您的coroutine painting(dispatchers.io)中连接{}
您会在dispatchers.io中做一些艰苦的事情,然后在 dispatchers.main 中更改您的观点

。 “ nofollow noreferrer”> developer.android.com/kotlin/coroutines

您不需要线程池。
只是比较性能。

fun main() {
val count = 100000

thread(count)

//  runBlocking {
//      coroutine(count)
//  }
}

private fun thread(count: Int){
    for (i in 0 until count) {
        thread {
            Thread.sleep(1000)
            println(i)
        }
    }
}

private fun CoroutineScope.coroutine(count: Int){
    for (i in 0 until count) {
        launch(Dispatchers.Main) {
            delay(1000)
            println(i)
        }
    }
}

Have you ever tryed kotlin coroutines?
It faster and you doun't need use pool.
Coroutines basics
.
Android include scopes for work in fragment like lifecycleScope and in viewModel
like viewModelScope.
Also you can create scope with Dispatchers CoroutineScope(Dispatchers.IO) or connect in your coroutine launch(Dispatchers.IO){}
You shold do something hard in Dispatchers.IO and change your views in Dispatchers.Main

You can read more here developer.android.com/kotlin/coroutines

You doun't need thread pool.
Just compare performance.

fun main() {
val count = 100000

thread(count)

//  runBlocking {
//      coroutine(count)
//  }
}

private fun thread(count: Int){
    for (i in 0 until count) {
        thread {
            Thread.sleep(1000)
            println(i)
        }
    }
}

private fun CoroutineScope.coroutine(count: Int){
    for (i in 0 until count) {
        launch(Dispatchers.Main) {
            delay(1000)
            println(i)
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文