だから、私は次のものを持っているとしましょうScheduledExecutorService
:
public class Foo
{
private ScheduledExecutorService exec;
public Foo()
{
exec = Executors.newScheduledThreadPool(NUM_OF_TASKS);
}
public void executeOnce()
{
exec.schedule(new Runnable(){
@Override
public void run()
{
Foo.this.doSomething();
}}, DELAY, TimeUnit.MILLISECONDS);
}
}
現在は、定期的なタスク (ディレクトリ ポーリングなど)exec
を実行するために使用されます。しかし、この 1 つのタスク (つまり) は1 回実行されますが、遅延が必要です。それで、このタスクを実行するために使用することにしましたが、これは良い設計ですか? 代わりに、 を作成してから を呼び出す必要がありましたか? 例えば、executeOnce
exec
newSingleThreadExecutor
shutdown
public void executeOnce()
{
// Execute task and wait 'til completion
ExecutorService exec = Executors.newSingleThreadExecutor();
try {
exec.submit(new Runnable(){
@Override
public void run()
{
try
{
Thread.sleep(DELAY);
} catch (InterruptedException e) {
}
Foo.this.doSomething()
}
}).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
// Shutdown executor service
exec.shutdownNow();
}
後者を実装するメリットはありますか?