Runable Callable Future

1. Callable difference with Runable

Java can be very easy to write multithreaded applications from the start of the first version released, and the introduction of asynchronous processing in the design. Thread class, Runnable interfaces and Java memory management, multi-threaded programming model makes it simple and direct.

But the Thread class and Runnable interface are not permitted to declare checked exceptions, can not define the return value. This is no return value a little bit of trouble. Can not declare throw checked exceptions are more some trouble.

public void run () method contract means you have to catch and handle checked exceptions. Even if you are careful to preserve the exception information for later examination (when capturing an exception), but there is no guarantee that all users of this class (Runnable objects) are read exception information.

You can also modify the getter Runnable implementation, so that they can be thrown task execution. However, this method is not very complicated in addition to safe and reliable, you can not force the user to call these methods, programmers will likely call join () method then waits for the end of the thread on the matter.

But now I do not worry, the above problem was finally resolved in 1.5. Callable interface and its introduction and their Future elegant solution to both problems to support the thread pool.

Regardless of which way to create threads, its essence is Callable interface Runable interface. Both are tasks that can be performed by other threads! ! The difference is:

(1) The method is defined Callable call (), and the method is defined Runnable run (). 

(2) Callable task execution returns a value, and the task is not Runnable return value. 

(3) call () method throws an exception, and the run () method throws an exception is not. 

(4) Callable task can be run to get a Future object.

2.Future

As mentioned above, Callable task returned Future object. Namely: Callable and Future produce a result, to get a result.

Future indicating an asynchronous result of the calculation . Future interface has the following methods:

  •     boolean cancel(boolean mayInterruptIfRunning)

Cancel the execution of the task. Parameter specifies whether to immediately interrupt task execution, or the end of the mission, etc.

  •     boolean isCancelled() 

Whether the task has been canceled, the task before it completed normally cancel, return true

  •     boolean isDone()

Whether the task has been completed. Note that if the task terminates normally, abnormal or canceled, will return true

  •     V get()

Wait for the task execution ends and then get the results V type. InterruptedException thread is interrupted abnormal, ExecutionException task execution exception if the task was canceled, will be thrown CancellationException

  •     V get(long timeout, TimeUnit unit) 

Get with the above features, like multi-set timeout. The timeout parameter specifies the timeout period, uint specified time unit, related to the class defined in the enumeration of TimeUnit. If the calculated time-out, will throw TimeoutException

If Future interface provides a method to detect the task is executed, executing the tasks waiting to get the results. You can also set task execution timeout , set the timeout of this method is to achieve key Java program execution timeouts.

So, if you need to set the maximum time code execution, that overtime be in line with Future interfaces with Java classes to implement thread pool ExecutorService

to sum up:

Runable suitable for fully asynchronous tasks, do not worry about the implementation of the exception error.

Callable applications that require the return of the results of the implementation of anomalies to be aware of the need to submit to the thread pool.

Future mainly Callable task execution thread pool, the returned results. It is possible to interrupt the execution of the task, has been waiting for the results, or wait for some time to obtain results.

 

A demo

package com.zyf.Future;

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;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureGetTimeOut1 {  
    public static void main(String[] args){  
        int timeout = 2;   
        ExecutorService executor = Executors.newSingleThreadExecutor();  
        Boolean result = false;     
        Future<Boolean> future = executor.submit(new TaskThread("发送请求"));//将任务提交给线程池
        try {     
            result = future.get(timeout, TimeUnit.SECONDS);
           // result = future.get(timeout, TimeUnit.MILLISECONDS); //1
            System.out.println("发送请求任务的返回结果: "+result);  //2
        } catch (InterruptedException e) {  
            System.out.println("线程中断出错。");  
            future.cancel(true);// 中断执行此任务的线程     
        } catch (ExecutionException e) {     
            System.out.println("线程服务出错。");  
            future.cancel(true);
        } catch (TimeoutException e) {// 超时异常     
            System.out.println("超时。");     
            future.cancel(true);  
        }finally{  
            System.out.println("线程服务关闭。");  
            executor.shutdown();  
        }  
    }  
      
    static class TaskThread implements Callable<Boolean> {    
        private String t;  
        public TaskThread(String temp){  
            this.t= temp;  
        }  
        public Boolean call() {  
            //for用于模拟超时
            for(int i=0;i<999999999;i++){  
                if(i==999999998){  
                    System.out.println(t+"成功!");  
                }  
                if (Thread.interrupted()){ //很重要  
                    return false;     
                }  
            }   
            System.out.println("继续执行..........");     
            return true;     
        }     
    }   
}

 

Published 504 original articles · won praise 610 · Views 1.14 million +

Guess you like

Origin blog.csdn.net/asdfsadfasdfsa/article/details/103811913