简体   繁体   中英

How to find when the thread completed?

Do I need to call future.get periodically to check whether the task is executed or not?

ExecutorService executor = Executors.newSingleThreadExecutor();

@SuppressWarnings("unchecked")
public void start(final file avo) throws IOException
{
    Future future = executor.submit(new Callable(){

    @Override
    public Object call() throws Exception {
        Condee conv = new Condee();
        return conv.doChange(file);
    });

    LOG.debug("Finished the execution serverion");
    executor.shutdown();


}

To check completion you can use future.isDone() , this needs to be constantly checked.

But if you use future.get() , this method will wait until finished and then return the result.

Add a call to this before executor.shutdown();

future.get();

This method will only return when it has completed.

Try to retrieve the value sing the get method. You will either get the result or an exception will be thrown. Here are the four possibilities when you call the get on future:

  1. You get the result value
  2. You get CancellationException - if the computation was cancelled (eg Future.cancel(true) is called)
  3. You get ExecutionException - if the computation threw an exception
  4. You get InterruptedException - if the current thread was interrupted while waiting (eg executor.shutdownNow() is called)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM