プログラムにそのようなコードがあります
for(int i = 0; i < 100000; i++) {
func(i);
}
i のほとんどの値では、func の持続時間は 1 秒未満ですが、一部の値では数分持続する場合があるため、持続時間が長すぎる場合は中断する必要があります。
どうやってやるの?
FutureTask は、タイムアウトのあるコードを実行するのに最適です。
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception {
/* Do here what you need */
return null; /* Or any instance */
}
}) {
};
try {
Object result = task.get(1, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
}
これが私の見方です。より少ないコード行でそれを行う方法があると確信していますが、これは簡単な解決策です
あなたが実行したい場合はfunc(i);
、Thread
別の話になります.
public class MainClass {
private static boolean riding, updated = false;
private static int timeout = 10000;
public static void main(String[] args) {
while (true) {
if (!riding){
long endTimeMillis = System.currentTimeMillis() + timeout;
func(endTimeMillis);
}
}
}
private static void func(long endTimeMillis) {
for (int i = 0; i < 9999; i++) {
if ((!riding && System.currentTimeMillis() < endTimeMillis) || updated) {
updated = false;
System.out.println("run method main function");
riding = true;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " > "
+ endTimeMillis);
if (System.currentTimeMillis() > endTimeMillis) {
updated = true;
System.out.println("overdue");
riding = false;
break;
}
}
}
riding = false;
}
}
別のスレッドで func() を開始し、join(long millis)
スレッドでメソッドを実行して、終了するまで 1 秒間待機することができます。ただし、スレッドは終了するまで実行されます (stop()
メソッドは非推奨です)。これの手段は、現在のスレッドで制御を取得し、適切に反応することです
時間がかかりすぎる関数を中断する 1 つの方法は、別のスレッドで実行することです。その後、1 秒後にそのスレッドにメッセージを送信して、停止するように指示できます。スレッドを使用しない場合は、 func を以下のコードに置き換えることで処理できます。
function process(int i, long maxMiliseconds) {
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - start < maxMiliseconds) {
//do your processing one step at a time
// return an answer if you have one.
}
//make some record of the fact that the process timed out for i.
return;
}