Java multithreading ~~~ Callable Interface

Source: Internet
Author: User

Java multithreading ~~~ Callable Interface

ThreadPoolExecutor provides another very powerful interface, that is, callable. This interface is similar to runnable,

The method of the interface is the call method, which can return values, making up for the sorrow that runnable cannot return values. In addition, this method can be used with ThreadP.

OolExecutor is used to obtain the Future interface. We can see from the interface name that the returned pointer is similar to a pointer to this thread.

You can use this Future interface to know the running status of the current thread, including whether the task has been completed, the current running status, and the returned value after the task is completed,

After each task is created, it is provided directly through the ThreadPoolExecutor submit method, which is very automatic. It's easy to stop.

. The following is an example of how to use this interface.


package com.bird.concursey.charpet6;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class FactorialCalculator implements Callable
 
   {private int number;public FactorialCalculator(int number) {super();this.number = number;}@Overridepublic Integer call() throws Exception {int result = 1;if(number == 0 || number == 1) {result = 1;}else{for(int i = 2; i <= number; i++) {result *= i;TimeUnit.MILLISECONDS.sleep(20);}}System.out.printf("%s: %d\n",Thread.currentThread().getName(),result);return result;}public static void main(String[] args) {ThreadPoolExecutor execute = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);List
  
   > results = new ArrayList
   
    >();Random random = new Random();for(int i = 0; i < 10; i++) {int number = random.nextInt(20);FactorialCalculator calcu = new FactorialCalculator(number);Future
    
      result = execute.submit(calcu);results.add(result);}do{System.out.printf("Main: Number of Completed Tasks:%d\n",execute.getCompletedTaskCount());for (int i=0; i
     
       result=results.get(i);System.out.printf("Main: Task %d: %s\n",i,result.isDone());}try {TimeUnit.MILLISECONDS.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}while(execute.getCompletedTaskCount() < results.size());System.out.printf("Main: Results\n");for(Future
      
        fus : results) {try {System.out.printf("Main: Task %d: %d\n",1,fus.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}execute.shutdown();}}
      
     
    
   
  
 

Remember to use shutdown. If you do not call this method, execute will always wait for running, even if there is no thread

Running. shundown does not close all threads immediately. It is only the table name. When other threads under its control are completed, execute will automatically shut down.

.

Related Article

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.