在n秒后调用该函数我使用下面的代码。
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
myFunction();
}
}, n);
这段代码uxcetute n次while语句是真的但是最后一次在那里排除了几秒钟"延迟"(保留,保留)。如何避免这种延迟"?可能这(上述)决定对我的任务不是一个好的决定吗?
完整代码在这里
public void onClick(View v){
if (v.getId() == bn.getId()) {
int[] j = { 1, 2 };
Random ran = new Random();
int randomstart = ran.nextInt(j.length);
if (randomstart == 1) {
new_game();
} else {
new_game();
aiClick();
}
return;
}
if (checkWin() == 2) {
winfinishrandom();
wins++;
calc();
MainActivity.this.draw_flag();
if (wins - loses == 10) {
wins = 0;
loses = 0;
draws = 0;
}
draw_line();
} else {
int[] x = { 1, 2 };
Random random = new Random();
int randomaray = random.nextInt(x.length);
if (randomaray == 1) {
draw_images();
aiClick();
} else {
draw_images();
int[] j = { 1000, 2000 };
Random ran = new Random();
int randomstart = ran.nextInt(j.length);
if (randomstart == 1000) {
// SLEEP 2 SECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
aiClick();
}
}, randomstart);
} else {
// SLEEP 2 SECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
aiClick();
}
}, randomstart);
}
}
}
}
答案 0 :(得分:1)
如果你想在n秒后运行一个方法,那么你不需要乱用创建新线程就有一个名为Thread.sleep(time in milliseconds)
的内置方法,其使用方法如下:
try {
Thread.sleep(1000); // 1000 ms = 1s however long you want it
} catch (InterruptedException e) {
e.printStackTrace(); // It can cause exception so needs to be in a try-catch statement
}
//Run the method here
someMethod();