Java multithreaded Future and callable class sample sharing _java

Source: Internet
Author: User

One, descriptive narration

When programming in multithreading. You may encounter a requirement that I want to get the data returned from each thread at the end of the thread that I started, and then do the same, and in this demand, the combination of future and callable is very useful.

Some people will say, I can use synchronization to complete this demand ah, in general, can indeed. But in a special case it doesn't:

Imagine that you've opened multiple threads to compute some data synchronously, but as you know, threads are competing for resources, that is to say. You turn on multiple threads to synchronize the data. In fact, the order of calculation between threads is not empty, of course, unless you have a lot of trouble to deal with it is not possible. In such a case. The combination of future and callable is the second choice.

Second, the sample

The examples of these two classes are actually very easy to use, mainly to see if they can find their application in practice. Code on:

 package test;
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;
  public class Feturecallabletest {private static Executorservice service = Executors.newfixedthreadpool (100);
  private static int count = 1;
    public static void Main (string[] args) throws Interruptedexception, executionexception {int sum = 0;
   
        for (int i = 0; i < i++) {future<integer> Future = service.submit (new callable<integer> () { @Override public Integer Call () throws Exception {System.out.println () Thread.CurrentThread (). Getn
          Ame ());
        return ++count;
      }
         
      });
      int f = future.get ();
      sum = f;
    System.out.println ("Future is" + f);
    } System.out.println ("sum is" + sum);
  Service.shutdownnow (); }
 
}

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.