JavaSE --- multithreaded --- Callable, Future

1 Overview

    After 1.1 JDK1.5, Java provides Callable interfaces , the interface provides a method call as a thread of execution, the call method can have a return value, the statement throw an exception;

          Therefore, we can directly Callable interface as the target to create a thread, but : Callable interface is a new interface that is not Runnable implementation class ;

              JDK1.5 then provides Future interface , and provides a FutureTask, Future interface implementation class (which implements the Runnable interface Thread can be used as a target);

    1.2  create, start, there is a thread return value :

          1.2.1 Creating Callable interface implementation class, implement call method;

          1.2.2 create an instance of the implementation class, and a FutureTask, encapsulation;

          1.2.3 FutureTask create an instance of Thread Thread instance as a target, calling start () open thread;

          1.2.4 calls FutureTask example of a method to obtain the return value of the sub-thread execution;

package com.an;

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

public class CallableImpl implements Callable {
    /**
     * 线程执行体
     * @return
     * @throws Exception
     */
    public Object call() throws Exception {
        int i=0;
        for (;i<10;i++){

        }
        return i;
    }

    public static void main(String[] args)throws Exception{
        for (int i=0;i<30;i++){
            System.out.println(Thread.currentThread().getName()+"="+i);
            if (i==5){
                FutureTask futureTask=new FutureTask(new CallableImpl());
                Thread thread=new Thread(futureTask,"有返回值的线程");
                thread.start();
                thread.join();
                System.out.println(futureTask.get());
            }
        }

    }
}

  

Guess you like

Origin www.cnblogs.com/anpeiyong/p/11023507.html