The difference and usage of callable,runnable _ multithreading

Source: Internet
Author: User
Tags commit throw exception

There are generally three ways to write multithreaded programs, thread,runnable,callable.

The difference between runnable and callable is:

(1) Callable the method specified is call (), and the Runnable method is run (). Where runnable can be presented to thread to wrap, directly start a thread to execute, while callable is generally submitted to Executeservice to execute.
(2) A callable task can return a value after execution, and Runnable's task is not to return a worthwhile
(3) Call method can throw an exception, the Run method can not
(4) Running the callable task can get a future object, C represents the result of an asynchronous computation.

Future provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to obtain the results of the calculation. Only the Get method can be used to obtain the results after the calculation is complete, and if the thread is not executed, the Future.get () method may block the execution of the current thread, and if the thread is abnormal, future.get () will throws Interruptedexception or executionexception; If the thread has been canceled, it will run out of Cancellationexception. Cancel is performed by the Cancel method. Isdone determine whether the task was completed properly or was canceled. Once the calculation is complete, the calculation can no longer be canceled. If you use Future for the sake of cancellation but do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.

/** * Through a simple test procedure to test runnable, callable through executor to schedule the relationship with future/package com.hadoop.thread;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Future; public class Runnableandcallable2future {public static void main (string[] args) {//Create a service Ex to perform a task
        Ecutorservice executor = Executors.newfixedthreadpool (3); try {//1.runnable Future return result to empty//create a runnable to schedule, wait for task execution, get return result future<?> ru
                    Nnable1 = Executor.submit (new Runnable () {@Override public void run () {
                System.out.println ("Runnable1 running.");
            }
            });

            System.out.println ("Runnable1:" + runnable1.get ());
            2.Callable can return results//commit and perform tasks via future, the task returns a future object at startup,//If you want the result of a task execution or an exception you can manipulate the future object Future<string> Future1 = executor.submit (new callable<string> () {@Override public String call () throws E
                xception {//TODO auto-generated Method stub return "Result=task1";
            }
            });

            Gets the result of the task, and if the Get method is called, the current thread waits for the task to execute before executing System.out.println ("Task1:" + future1.get ()); 3.
            Call Cancel on the callable can break//commit and perform a task on the task, and the task starts with a future object,//If you want the result of a task execution or an exception to manipulate the future object
                future<string> Future2 = executor.submit (new callable<string> () {@Override Public String Call () throws Exception {try {while Tru
                            e) {System.out.println ("Task2 running.");
                        Thread.Sleep (50); } catch (Interruptedexception e) {System.out.printlN ("interrupted Task2.");
                Return to "Task2=false";

            }
            }); Wait 5 seconds before stopping the second task.
            Because the second task carried out is an infinite cyclic thread.sleep (10);

            System.out.println ("Task2 Cancel:" + Future2.cancel (true)); 4. Throw an exception when callable with a future nothing is going to get the output of the third task, because performing a third task causes an exception//So the following statement will cause an exception to be thrown Futu re<string> future3 = executor.submit (new callable<string> () {@Override publi
                C String Call () throws Exception {throw new Exception ("Task3 throw exception!");
            }

            });
        System.out.println ("TASK3:" + future3.get ());
        catch (Exception e) {System.out.println (e.tostring ());
    //Stop Task Execution Service Executor.shutdownnow ();
 }
}

The results of the implementation are as follows:

Runnable1 running.
Runnable1:null
task1:result=task1
task2 running.
Task2 cancel:true
interrupted task2.
Java.util.concurrent.ExecutionException:java.lang.Exception:Bad Flag value!

Futuretask is a runnablefuture, that is, the realization of the Runnbale and futrue these two interfaces, in addition it can also be packaged runnable and callable, so generally speaking is a compliance with the body, It can be executed directly through the thread wrapper, can also be submitted to the Executeservice to execute, and can also return the execution result via v get (), when the thread body does not finish, the main thread blocks the wait, and returns the result directly after execution.

public class Futuretasktest {/** * @param args */public static void main (string[] args) {Cal lable<string> task = new callable<string> () {public String call () {SYSTEM.OUT.PR
                Intln ("Sleep Start");
                try {thread.sleep (1000 * 10); catch (Interruptedexception e) {//TODO auto-generated catch block E.printstack
                Trace ();
                } System.out.println ("Sleep End.");
            Return "Time=" + system.currenttimemillis ();

        }
        };
        Execute futuretask<string> ft = new futuretask<string> (Task) directly using thread;
        Thread t = new thread (ft);
        T.start ();
            try {System.out.println ("Waiting execute result");
        SYSTEM.OUT.PRINTLN ("result =" + Ft.get ()); catch (Interruptedexception e) {//TODO auto-generated CATCH Block E.printstacktrace ();
        catch (Executionexception e) {//TODO auto-generated catch block E.printstacktrace ();
        ///Use executors to perform System.out.println ("=========");
        futuretask<string> ft2 = new futuretask<string> (Task);
        Executors.newsinglethreadexecutor (). Submit (FT2);
            try {System.out.println ("Waiting execute result");
        SYSTEM.OUT.PRINTLN ("result =" + Ft2.get ());
        catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (Executionexception e) {//TODO auto-generated catch block E.printstacktrace (); }

    }
}

The results of the implementation are as follows:

Waiting execute result sleep
start.
Sleep end.
result = time=1370844662537
=========
Waiting execute result sleep
start.
Sleep end.
result = time=1370844672542

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.