Vii. Callable and future

Source: Internet
Author: User

Callable a task that returns a result and may throw an exception. The implementing person defines a method called call without any parameters .

The callable interface is similar to runnable.

Example one:

Runnable Interface Example:

New Thread (new  Runnable () {            @Override            publicvoid  run () {                System.out.println (Thread.CurrentThread (). GetName ()+ ": Hello");            }        ). Start ();

Callable Interface Example:

Callable<string> callable =NewCallable<string> () {//The generics here are the same as the return result you want (the return value of the call method)@Override PublicString Call ()throwsException {//can throw an exception           returnThread.CurrentThread (). GetName () + "Hello"; }}; Futuretask<String> Futuretask =NewFuturetask<string> (callable);//The generics here are consistent with the generic type in callable, that is, the call () return value type. NewThread (Futuretask). Start ();//The Futuretask implements the Runnable interface  and the future interface, which is used to receive the return value. System.out.println (Futuretask.get ());//Get return results

The difference between the Runnable interface and the callable interface is that the method of task invocation is run () and call (), run () has no return value, no exception is defined (so you cannot throw an exception), and the Calling () method has a return value and can throw an exception.

Use the thread pool to perform callable tasks:

Example two:

 Public classCallabletest { Public Static voidMain (string[] args)throwsException {//to create a single thread poolExecutorservice Executorservice =Executors.newsinglethreadexecutor (); //The execute (Runnable Runnable) method is not used here, but instead of the submit (callable<string> Task), the usage is similar to Runnable, with only the return value, Use the future interface to receive the return value. future<string> future = Executorservice.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {return"Hello";        }        }); System.out.println ("Get Results:" +future.get ());//get the return result of the method execution     }}


Example three:

Similar to the above, just the following execution of multiple tasks, above the execution of a single task.

 Public classCallableandfuturetest {/*** * Perform callable Tasks @Description online pool *@authorFulaizhi * @date June 18, 2016 PM 2:37:19 *@paramargs *@throwsException*/     Public Static voidMain (string[] args)throwsException {executorservice ExecutorService2=Executors.newcachedthreadpool (); Completionservice<Integer> Completionservice =NewExecutorcompletionservice<integer>(EXECUTORSERVICE2);  for(inti = 1; I <= 10; i++) {            Final inttemp =i; Completionservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000)); returntemp;        }            }); }         for(inti = 0; i<10;i++){            /*** Returns the result of first execution and, if none is completed, waits for the result of the first completed task to return * and then the next call waits for a new return result until the result is returned.             If no result is returned, it will wait until it continues. */ Future<Integer> future =Completionservice.take ();         System.out.println (Future.get ()); }    }
}

Vii. Callable and future

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.