Use ExecutorService and thread pool to handle Callable thread - Java Thread

Java examples for Thread:ExecutorService

Description

Use ExecutorService and thread pool to handle Callable thread

Demo Code


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class FutureTaskTest
{
    //from   w  w w  .  j  ava  2 s .  c  o  m
    private void testFutureTaskInAnotherThread()
    {
        System.out.println("FutureTaskTest.testFutureTask");
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<String> result = executor.submit(new Callable<String>()
        {

            @Override
            public String call()
                throws Exception
            {
                Thread.currentThread().sleep(2000l);
                return "done result";
            }
        });
        try
        {
            System.out.println(result.get());
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args)
    {
        FutureTaskTest test = new FutureTaskTest();
        test.testFutureTaskInAnotherThread();
    }
}

Related Tutorials