Java multithreaded Future and Callable class examples are Shared

  • 2020-04-01 04:36:16
  • OfStack

First, descriptive narration

      The & # 8203; When programming in multiple threads. The combination of Future and Callable comes in handy when I want to get the data from each thread at the same time when all the threads I started are finished, and then do the same thing.

Some people will say, well, I can use synchronization to complete this requirement, and in general I can. But not in one particular case:

      The & # 8203; Imagine that you have multiple threads running to compute some data synchronously, but everyone knows that threads compete for resources, that is. When you start multiple threads to synchronize data. In fact, the order of computation between threads is not null, unless of course you have to take a lot of trouble to process it. In this case. The combination of Future and Callable is the perfect choice.

Second, the sample

The examples of these two classes are actually very easy, mainly depending on whether you can find their use in practice. The code:


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 < 100; i++) {
      Future<Integer> future = service.submit(new Callable<Integer>(){
   
        @Override
        public Integer call() throws Exception {
          System.out.println(Thread.currentThread().getName());
          return ++count;
        }
         
      });
      int f = future.get();
      sum += f;
      System.out.println("future is " + f);
    }
    System.out.println("sum is " + sum);
    service.shutdownNow();
  }
 
}


Related articles: