java - 应用程序在主线程上做太多工作

标签 java android multithreading

我尝试执行下面的方法,但我不断收到错误消息“跳过 n 帧!应用程序可能在其主线程上做了太多工作。”我试过将 for 和 while 循环分解成这样的线程

 Thread thread = new Thread() {
@Override
public void run() {
    try {
        // for or while loop here
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
};

thread.start();

然而,这也根本不起作用。对此有任何可能的修复吗?

public void newSim(int x) {
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    int buttonWidth = (int) (width * 0.15);
    int buttonWidth1 = (int) (width * 0.20);
    int buttonHeight1 = (int) (height * 0.20);

    ArrayList<Point> intersection = new ArrayList<Point>();
    final ArrayList<Point> location = new ArrayList<Point>();

    int constraint = 0;

    int xC = width - buttonWidth1;
    int yC = height - buttonWidth1;

    for (int i = 0; i < x; i++) {
        for (int j = 0; j < x; i++) {
            location.add(new Point(i, j));
            constraint++;
        }
    }

    for (int i = 0; i < x; i++) {
        Random random = new Random();
        Point point = new Point();
        point = location.remove(random.nextInt(constraint));
        while (intersection.contains(point)) {
            intersection.add(point);
            point = location.remove(random.nextInt(constraint));
        }
    Button but1 = new Button(this);
    but1.setText(String.valueOf(i));
    RelativeLayout r = (RelativeLayout) findViewById(R.id.playLayout);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonWidth);
    layoutParams.setMargins(0, 0, buttonWidth, buttonWidth);
    but1.setLayoutParams(layoutParams);
    r.addView(but1);
    constraint--;
    }
}

最佳答案

你在 for 循环中运行什么?新模拟人生()?该方法具有 UI 操作。所以它不能在不同的线程中运行。

关于java - 应用程序在主线程上做太多工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34778096/

相关文章:

android - 如何从存储在 android 的 sharedPreference 中的数组列表中删除项目?

java - 同步对象在 notifyAll() 之前未被线程锁定

android - 无法在线程内创建处理程序

java - 使用 RenderScript 库编译时出现错误 : llvm-rs-cc. exe'' 以非零退出值完成 -1073741515

java - 具有单个参数的 Spring Data JPA "OR"

android - 如何在线性布局中均匀地分离 ImageView

android - 我如何使用 Android EffectFactory 类?

java - JTree节点编辑路径比较始终为真

java - API 是否应该抛出 NullPointerExceptions

java - 使用 Java8 匹配方法比较两个列表