zoukankan      html  css  js  c++  java
  • Java FutureTask Example Program(Java FutureTask例子)

    Sometime back I wrote a post about Java Callable Future interfaces that we can use to get the concurrent processing benefits of threads as well as they are capable of returning value to the calling program.

    FutureTask is base concrete implementation of Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled. We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously.

    Let’s see the example of FutureTask with a simple program.

    Since FutureTask requires a callable object, we will create a simple Callable implementation.

    
    package com.journaldev.threads;
    

    import java.util.concurrent.Callable;

    public class MyCallable implements Callable<String> {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> waitTime;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyCallable</span><span class="hljs-params">(<span class="hljs-keyword">int</span> timeInMillis)</span></span>{
    	<span class="hljs-keyword">this</span>.waitTime=timeInMillis;
    }
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">call</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
    	Thread.sleep(waitTime);
        <span class="hljs-comment">//return the thread name executing this callable task</span>
        <span class="hljs-keyword">return</span> Thread.currentThread().getName();
    }
    

    }

    Here is an example of FutureTask method and it’s showing commonly used methods of FutureTask.

    
    package com.journaldev.threads;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.FutureTask;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class FutureTaskExample {
    
    	public static void main(String[] args) {
    		MyCallable callable1 = new MyCallable(1000);
    		MyCallable callable2 = new MyCallable(2000);
    
    		FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
    		FutureTask<String> futureTask2 = new FutureTask<String>(callable2);
    
    		ExecutorService executor = Executors.newFixedThreadPool(2);
    		executor.execute(futureTask1);
    		executor.execute(futureTask2);
    		
    		while (true) {
    			try {
    				if(futureTask1.isDone() && futureTask2.isDone()){
    					System.out.println("Done");
    					//shut down executor service
    					executor.shutdown();
    					return;
    				}
    				
    				if(!futureTask1.isDone()){
    				//wait indefinitely for future task to complete
    				System.out.println("FutureTask1 output="+futureTask1.get());
    				}
    				
    				System.out.println("Waiting for FutureTask2 to complete");
    				String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
    				if(s !=null){
    					System.out.println("FutureTask2 output="+s);
    				}
    			} catch (InterruptedException | ExecutionException e) {
    				e.printStackTrace();
    			}catch(TimeoutException e){
    				//do nothing
    			}
    		}
    		
    	}
    
    }
    

    When we run above program, you will notice that it doesn’t print anything for sometime because get() method of FutureTask waits for the task to get completed and then returns the output object. There is an overloaded method also to wait for only specified amount of time and we are using it for futureTask2. Also notice the use of isDone() method to make sure program gets terminated once all the tasks are executed.

    Output of above program will be:

    Copy
    FutureTask1 output=pool-1-thread-1 Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete FutureTask2 output=pool-1-thread-2 Done

    As such there is no benefit of FutureTask but it comes handy when we want to override some of Future interface methods and don’t want to implement every method of Future interface.

  • 相关阅读:
    Redis使用手册
    log4j.properties 输出指定类日志
    Maven中Jar包冲突,不让某个Jar包打入到工程中
    Cannot refer to the non-final local variable user defined in an enclosing scope
    PANIC: Missing emulator engine program for ‘x86’ CPU.
    Android studio 不能创建Activity等文件
    jenkins打maven包,出现Module Builds里面部分模块没有启动问题
    CentOS7 SFTP服务安装和使用
    记一次阿里云服务器被挖矿程序植入处理(简单记录下)
    利用阿里云高可用虚拟ip+keepalived+mha实现两台mysql的高可用
  • 原文地址:https://www.cnblogs.com/jpfss/p/9373312.html
Copyright © 2011-2022 走看看