【发布时间】:2021-11-12 03:48:47
【问题描述】:
大家好,我想将以下代码放在与 ui 线程不同的新线程中,但 android studio 给出了一个错误,即需要将变量声明为 final。当我声明变量 final 时,它会使我的应用程序崩溃。请问如何在不声明变量 final 的情况下启动新线程。
public void checkUpTaking(int position, int rowImpact, int takenPawn) { //taken pawn: -1 = brown, 1 = white
if (position > 10) { //if you'll try to take from the last row - array out of bounds
if (position % 5 != 0 && playableTile[position - 1 - 4 - rowImpact].getIsTaken() == takenPawn &&
playableTile[position - 1 - 9].getIsTaken() == 0) {
checkTreeNodes(position, position - 9, position-4-rowImpact); //checking possible mandatory moves before clicking pawn
}
if ((position - 1) % 5 != 0 && playableTile[position - 1 - 5 - rowImpact].getIsTaken() == takenPawn &&
playableTile[position - 1 - 11].getIsTaken() == 0) {
checkTreeNodes(position, position - 11, position-5-rowImpact);
}
}
}
我正在尝试在不使我的变量成为最终变量的情况下实现这样的目标
public void checkUpTaking(int position, int rowImpact, int takenPawn) { //taken pawn: -1 = brown, 1 = white
new Thread(new Runnable() {
@Override
public void run() {
if (position > 10) { //if you'll try to take from the last row - array out of bounds
if (position % 5 != 0 && playableTile[position - 1 - 4 - rowImpact].getIsTaken() == takenPawn &&
playableTile[position - 1 - 9].getIsTaken() == 0) {
checkTreeNodes(position, position - 9, position-4-rowImpact); //checking possible mandatory moves before clicking pawn
}
if ((position - 1) % 5 != 0 && playableTile[position - 1 - 5 - rowImpact].getIsTaken() == takenPawn &&
playableTile[position - 1 - 11].getIsTaken() == 0) {
checkTreeNodes(position, position - 11, position-5-rowImpact);
}
}
}
}).start();
}
【问题讨论】:
-
"without make my variable final" 我不明白为什么你需要将它们设为final。是否还有其他代码未显示重新分配参数的位置?
-
是的,我正在尝试制作跳棋游戏,但我正在尝试解决 Anr 错误。所以我试图减少我的主线程上的工作量。我的代码很长,它的主体受限于 stackoverflow
-
但是您在此处显示的代码doesn't require
final。如果此方法中有其他代码重新分配这些变量,简单的答案是提取您显示的代码或您没有提取到另一个方法中的代码。 -
为什么不能将变量声明为final?我不确定android是否有与java不同的规则。您可以将 final 放在方法参数上。
标签: java multithreading android-studio arraylist