"Turn" Callable and Future

Why Callable?

There are two ways to create threads, one is by extending the Thread class, and the other is through the use of Runnable create threads.

However, Runnable missing a feature that, when the thread terminates (ie run () to complete), we can not make the thread return results. To support this functionality, Java provides Callable interface.

Callable vs Runnable

  • Runnable achieve returns nothing need to implement the run () method, and for a Callable, need to implement the call () method returns the results after completion. Please note that you can not use Callable create a thread, the thread can only be used to create Runnable.
    • Why not create a thread involves ExecutorService the submit method
  • Another difference is the call () method can throw an exception, and the run () can not.

  • This is an example Callable code, in this example about 0 - Returns a random delay of 4 seconds.

// Java program to illustrate Callable 
// to return a random number 
import java.util.Random; 
import java.util.concurrent.Callable; 
import java.util.concurrent.FutureTask; 

class CallableExample implements Callable 
{ 

    public Object call() throws Exception 
    { 
        // Create random number generator 
        Random generator = new Random(); 

        Integer randomNumber = generator.nextInt(5); 

        // To simulate a heavy computation, 
        // we delay the thread for some random time 
        Thread.sleep(randomNumber * 1000); 

        return randomNumber; 
    } 
} 

Future

When the call () method is completed, the answer must be stored in the main thread known object, so you know that the main thread of the thread is returned.

The program will later be stored and how to obtain this result?

To do this, you can use the Future object. Future results will be stored as an object - it may temporarily save the results, but in the future will be saved (once Callable return). Therefore, Future is basically the main thread can track the progress and results of a way other threads. To implement this interface must be rewritten five methods, but due to the following example uses a specific implementation of the library, so this method only lists important.

In fact, Callable and Future do two things

  • Callable and Runnable similar, because it encapsulates the task to run on a different thread
  • Future used to store the results obtained from another thread.

The method needs to be rewritten

  • public boolean cancel (boolean mayInterrup): To stop the task. If you have not started, it will stop the task. If you have started, you will only interrupt task when mayInterrupt is true.
  • public Object get() throws InterruptedException,ExecutionException: To get the results of the task. If the task is complete, it returns the result immediately, otherwise it will wait for the task to complete, and returns the result.
  • public boolean isDone(): If the task is completed, it returns true, false otherwise

To create a thread, you need Runnable interface. In order to get the results, we need to Future class.

Java library has a specific type of a FutureTask, , the type implements Runnable and Future, and easily combine both functions.

FutureTask can be created by providing Callable its constructor. Then, the object is supplied to FutureTask Thread constructor to create a Thread object.

Again, it can not be used directly Callable create threads.

This is the complete sample code uses the Callable and FutureTask.

// Java program to illustrate Callable and FutureTask 
// for random number generation 

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class CallableExample implements Callable {

    public Object call() throws Exception {
        Random generator = new Random();
        Integer randomNumber = generator.nextInt(5);

        Thread.sleep(randomNumber * 1000);

        return randomNumber;
    }

}

public class CallableFutureTest {
    public static void main(String[] args) throws Exception {

        // FutureTask implements both Runnable and Future 
        FutureTask[] randomNumberTasks = new FutureTask[5];

        for (int i = 0; i < 5; i++) {
            Callable callable = new CallableExample();

            // 用 Callable 创建 FutureTask
            randomNumberTasks[i] = new FutureTask(callable);

            // 在实现Runnable时,使用FutureTask创建线程
            Thread t = new Thread(randomNumberTasks[i]);
            t.start();
        }

        for (int i = 0; i < 5; i++) {
            //  Future, we can call get() 
            System.out.println(randomNumberTasks[i].get());
            // 该方法将阻塞直到获得结果。
            // get方法可以引发检查异常,例如被中断时。 这就是将throws子句添加到main的原因
        }
    }
} 

Guess you like

Origin www.cnblogs.com/antonzhao/p/12505356.html