Callable interface schematic and test

package t1;

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

class MyCallable implements Callable<Integer> {

@Override
public Integer call() throws Exception {
System.out.println("*****come in Callable");
TimeUnit.SECONDS.sleep(3);
return 1000;
}

}

public class CallableDemo {

static void main public (String [] args) throws InterruptedException, ExecutionException {
// implementation class FutureTask to RunnableFuture, RunnableFuture sub Runnablede interface
// constructor arguments are FutureTask Callable interface.
Such Thread // constructor can be used Runnablede subclass FutureTask configured to construct comprising Callable
// This is an adapter mode
// FutureTask the get () method gets the return value Callable thread of execution, appears FutureTask the reason
// task is to break down and then merge the results
// FutureTask the get () will be blocked, it is generally placed at the end get results, may also have spin-lock manner while loop.
A FutureTask, <Integer> = new new FutureTask a FutureTask, <> (new new MyCallable ());
new new the Thread (FutureTask) .start ();
new new the Thread (FutureTask) .start (); // grab a plurality of threads futureTask, does not perform two, if the two have to perform, requires two open FutureTask
int RESULT1 = 100;
the while (futureTask.isDone ()) // blocked here, once the calculation is complete, the value
;
int result2 = futureTask.get();
System.out.println(result1 + result2);

}

}

 

Output:

*****come in Callable
1100

Guess you like

Origin www.cnblogs.com/dengw125792/p/12630075.html