質問

このトピックは十分に正確ではないかもしれないと思いますが、非常に短い方法でそれを説明する方法が本当にわかりません...

私がやりたいのは次のとおりです。分析(Javaで)を実行し、返品値を与えようとするプロセスがありますが、分析全体に時間制約があります。たとえば10秒です

分析が10代以内の結果をもたらす場合、結果を返します。そうでなければ、10秒に達するときに時間を増やして、プロセスを停止してダミー値を返します

私はこの分野の初心者です。どんな提案でも歓迎されます。

役に立ちましたか?

解決

You can use FutureTask to create a job and request the result within a particular time (using get() with a timeout). If that time window is breached, then you'll get an exception.

At that point you can then call the cancel() method with the parameter set to true to force an interruption and cancel the underlying task.

Object result = DUMMY;
try {
   result = futureTask.get(5, TimeOut.SECONDS);
}
catch (TimeoutException e) {
   futureTask.cancel(true);
}

他のヒント

You could use a timer (java.util.Timer), which you could notify of the thread, and then when the timer expired it could tell the thread to stop.

A better solution would be to spawn the process off into it's own thread, and then tell your main thread to wait on the processing thread and sleep for 10 seconds. When it finishes, you can send the thread a stop signal. Note: I would not use the stop() method, and instead send either a signal or set a value through a synchronized method that gets checked every so often during the execution.

Take a look at java.util.concurrent.Future, particularly the get(long timeout, TimeUnit unit) method:

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

I had a similar issue when writing a game AI that used Minimax, the requirement was to return within 5 seconds with a move. I tested using a Timer to set a boolean flag in my code which was checked periodically, there were no performance gains over using a call to System.currentTimeMillis().

So if the dummy value you want to return is actually some partial solution, I recommend that you store the system's time in a long and check periodically to see if you ten seconds are up and return whatever value you have left.

Otherwise, use FutureTask and call the get method on it with your timeout. One thing Brian didn't mention though is that your code doing the processing has to check if it has been interrupted periodically in order to actually stop execution early.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top