gpt4 book ai didi

java - UI线程和图像处理

转载 作者:太空狗 更新时间:2023-10-29 14:15:50 30 4
gpt4 key购买 nike

我有一个优先级设置为 Thread.MIN_PRIORITY + 1 的线程,它为我做一些图像处理(调整大小、读取和写入)。

我注意到,每当该线程处理图像时,我的 UI 线程中的动画就会开始断断续续并停止。

优先级足够低,因此动画应该比该线程具有更高的优先级,而且我的 CPU 肯定不会缺少资源。

发生这种情况有什么特别的原因吗?


编辑 - 我的线程:

public class WorkerQueue extends Thread {
public Handler handler;
int priority = Thread.MIN_PRIORITY + 1;
private static WorkerQueue self = null;

public static WorkerQueue getInstance() {
if (self == null) {
self = new WorkerQueue();
self.start();
self.setPriority(priority);
}

return self;
}

@Override
public void run() {
Looper.prepare();
handler = new Handler();
handler.getLooper().getThread().setPriority(priority);
Looper.loop();
}

public synchronized void enqueueTask(final Worker task) {
handler.post(new Runnable() {
@Override
public void run() {
task.run();
}
});
}
}

最佳答案

可能是GC。

图像处理可能需要大量内存分配和随之而来的垃圾收集。 Android 中的 GC 使用标记和清除算法,该算法要求 VM 停止执行您的程序 - 您可以看到这如何导致 UI 卡顿。参见示例 this answer和这个现价报价:

The main disadvantage of the mark-and-sweep approach is the fact that that normal program execution is suspended while the garbage collection algorithm runs. In particular, this can be a problem in a program that interacts with a human user or that must satisfy real time execution constraints. For example, an interactive application that uses mark-and sweep garbage collection becomes unresponsive periodically.

您可以通过查看 logcat 来确认这是否正确 - 这会为每次 GC 打印出一条消息,此时,UI 线程将被阻塞。

如果是 GC,那么解决它的一种方法是查看您的内存分配模式,看看是否可以减少内存流失,也许通过重用缓冲区和工作内存。

关于java - UI线程和图像处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317659/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com