JAVA---Multi-thread callable and Future,futuretask, and its simple application __java

Source: Internet
Author: User

Runnable encapsulates a task that runs asynchronously, without an asynchronous method with parameters that do not have return values. Callable and runnable are similar, but there are return values, and the callable interface is a parameterized type, with only one method call. The parameter type is the return value type. In fact, the interface will run a task that produces a result.

    Package java.util.concurrent;
    Public interface Callable<v> {
        /**
         * Computes a result
         *
         * @return computed result
         /
        V Call () throws Exception;
    }

Future saves the results of an asynchronous computation, you can start a calculation, give the future object to a thread, and then forget about it. The owner of the future object can obtain her after the result is calculated.
The future interface has the following methods:

    Package java.util.concurrent;
    Public interface Future<v> {
        Boolean cancel (Boolean mayinterruptifrunning);/Cancel the task that is executing

        boolean IsCancelled ()//whether the current task cancels

        Boolean isdone ()//whether the current task completes

        V get () throws Interruptedexception, executionexception;//Gets the result, if the result is not, blocks straight
    //To get the real result, and if the specified time is exceeded, it throws an exception

        V get (long timeout, timeunit)
        Throws Interruptedexception, Executionexception, timeoutexception;

    }

The call to the Get () method is blocked, knowing that the calculation is complete, and if the second method's call times out before the calculation completes, throw the timeoutexception exception. If the calculation is completed, the Get () method returns immediately.
You can cancel the calculation with the Cancel method.
The Futuretask wrapper is a very convenient mechanism to convert callable into future and runnable, and to implement both interfaces.

    Callable<integer> mcall= ...;
    futuretask<integer> task = new futuretask<integer> (mCall);
    Thread t = new thread (Task);
    T.start ();

This is the usual way to use futuretask.
Analysis in a bundle inheritance relationship:

Futuretask<v> Implements Runnablefuture<v>

Use recursion to query the total number of files in a directory that contain a keyword.

Package com.test.thread;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.util.ArrayList;
Import Java.util.Scanner;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.Future;

Import Java.util.concurrent.FutureTask; /** * Core class, implements callable interface, returns the number of files containing keyword in a directory * @author Tony/public class Matchcounter implements Callable<integer
    >{/** * Path * * Private File directory;
    /** * Key word */private String keyWords;

    /** * Final return result/private int count;
        Public Matchcounter (File directory, String keyWords) {super ();
        this.directory = Directory;
    This.keywords = KeyWords;
        @Override public Integer Call () throws Exception {count = 0;
            try {file[] files = directory.listfiles ();
            arraylist<future<integer>> results = new arraylist<future<integer>> (); For (File file: files) {if (File.isdirectory ()) {//If the path also has a subpath, recursive invocation, each time traversing a folder new open thread Encapsulation futuretask<integer> timely fetch to return value matchcounter counter = new Matchcounter (fil
                    E, keyWords);
                    futuretask<integer> task = new futuretask<integer> (counter);
                    Results.add (Task);
                    Thread t = new thread (Task);
                T.start ();
                    else {if (search (file)) {count++;
                }} for (Future<integer> result:results) {
            count+= Result.get ();
        } catch (Interruptedexception e) {e.printstacktrace ();
    return count;
     /** * To determine if the file contains keywords keyword * @param file * @return/public boolean search (file file) {   try {Scanner Scanner = new Scanner (new FileInputStream (file));
            Boolean isfound = false;
                while (!isfound && scanner.hasnextline ()) {String line = Scanner.nextline ();
                if (Line.contains (keyWords)) {Isfound = true;
        } return isfound;
        catch (IOException e) {return false;
 }

    }

}
package com.test.thread;
Import Java.io.File;
Import java.util.concurrent.ExecutionException;

Import Java.util.concurrent.FutureTask;  public class Futuretest {public static void main (string[] args) {matchcounter counter = new Matchcounter (new
        File ("c:\\users\\tony\\git\\"), "view");
        futuretask<integer> task = new futuretask<integer> (counter);
        Thread thread = new thread (Task);
        Thread.Start (); try {System.out.println (Task.get () + "matching files.");} catch (Interruptedexception |
        Executionexception e) {e.printstacktrace (); }
    }
}

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.